diff --git a/sdk/storage/azure-storage-file-share/MANIFEST.in b/sdk/storage/azure-storage-file-share/MANIFEST.in index b67e266799ba..1da294d9d659 100644 --- a/sdk/storage/azure-storage-file-share/MANIFEST.in +++ b/sdk/storage/azure-storage-file-share/MANIFEST.in @@ -1,7 +1,7 @@ include *.md -include azure/__init__.py -include azure/storage/__init__.py include LICENSE +include azure/storage/fileshare/py.typed recursive-include tests *.py recursive-include samples *.py *.md -include azure/storage/fileshare/py.typed +include azure/__init__.py +include azure/storage/__init__.py diff --git a/sdk/storage/azure-storage-file-share/_metadata.json b/sdk/storage/azure-storage-file-share/_metadata.json new file mode 100644 index 000000000000..48cc0626e1f3 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersion": "2026-06-06", + "apiVersions": { + "Storage.File": "2026-06-06" + } +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-file-share/apiview-properties.json b/sdk/storage/azure-storage-file-share/apiview-properties.json new file mode 100644 index 000000000000..1408a4caf6a8 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/apiview-properties.json @@ -0,0 +1,160 @@ +{ + "CrossLanguagePackageId": "Storage.File", + "CrossLanguageDefinitionId": { + "azure.storage.fileshare.models.AccessPolicy": "Storage.File.AccessPolicy", + "azure.storage.fileshare.models.ClearRange": "Storage.File.ClearRange", + "azure.storage.fileshare.models.CorsRule": "Storage.File.CorsRule", + "azure.storage.fileshare.models.DirectoryItem": "Storage.File.DirectoryItem", + "azure.storage.fileshare.models.Error": "Storage.File.Error", + "azure.storage.fileshare.models.FileItem": "Storage.File.FileItem", + "azure.storage.fileshare.models.FileProperty": "Storage.File.FileProperty", + "azure.storage.fileshare.models.FileRange": "Storage.File.FileRange", + "azure.storage.fileshare.models.FilesAndDirectoriesListSegment": "Storage.File.FilesAndDirectoriesListSegment", + "azure.storage.fileshare.models.HandleItem": "Storage.File.HandleItem", + "azure.storage.fileshare.models.KeyInfo": "Storage.File.KeyInfo", + "azure.storage.fileshare.models.ListFilesAndDirectoriesSegmentResponse": "Storage.File.ListFilesAndDirectoriesSegmentResponse", + "azure.storage.fileshare.models.ListHandlesResponse": "Storage.File.ListHandlesResponse", + "azure.storage.fileshare.models.ListSharesResponse": "Storage.File.ListSharesResponse", + "azure.storage.fileshare.models.Metrics": "Storage.File.Metrics", + "azure.storage.fileshare.models.RetentionPolicy": "Storage.File.RetentionPolicy", + "azure.storage.fileshare.models.ShareFileRangeList": "Storage.File.ShareFileRangeList", + "azure.storage.fileshare.models.ShareItemInternal": "Storage.File.ShareItemInternal", + "azure.storage.fileshare.models.ShareNfsSettings": "Storage.File.ShareNfsSettings", + "azure.storage.fileshare.models.ShareNfsSettingsEncryptionInTransit": "Storage.File.ShareNfsSettingsEncryptionInTransit", + "azure.storage.fileshare.models.SharePermission": "Storage.File.SharePermission", + "azure.storage.fileshare.models.SharePropertiesInternal": "Storage.File.SharePropertiesInternal", + "azure.storage.fileshare.models.ShareProtocolSettings": "Storage.File.ShareProtocolSettings", + "azure.storage.fileshare.models.ShareSmbSettings": "Storage.File.ShareSmbSettings", + "azure.storage.fileshare.models.ShareSmbSettingsEncryptionInTransit": "Storage.File.ShareSmbSettingsEncryptionInTransit", + "azure.storage.fileshare.models.ShareStats": "Storage.File.ShareStats", + "azure.storage.fileshare.models.SignedIdentifier": "Storage.File.SignedIdentifier", + "azure.storage.fileshare.models.SignedIdentifiers": "Storage.File.SignedIdentifiers", + "azure.storage.fileshare.models.SmbMultichannel": "Storage.File.SmbMultichannel", + "azure.storage.fileshare.models.StorageServiceProperties": "Storage.File.StorageServiceProperties", + "azure.storage.fileshare.models.StringEncoded": "Storage.File.StringEncoded", + "azure.storage.fileshare.models.UserDelegationKey": "Storage.File.UserDelegationKey", + "azure.storage.fileshare.models.NfsFileType": "Storage.File.NfsFileType", + "azure.storage.fileshare.models.StorageErrorCode": "Storage.File.StorageErrorCode", + "azure.storage.fileshare.models.FilePermissionFormat": "Storage.File.FilePermissionFormat", + "azure.storage.fileshare.models.ShareTokenIntent": "Storage.File.ShareTokenIntent", + "azure.storage.fileshare.models.FilePropertySemantics": "Storage.File.FilePropertySemantics", + "azure.storage.fileshare.models.ListFilesIncludeType": "Storage.File.ListFilesIncludeType", + "azure.storage.fileshare.models.AccessRight": "Storage.File.AccessRight", + "azure.storage.fileshare.models.CopyStatus": "Storage.File.CopyStatus", + "azure.storage.fileshare.models.FileRangeWriteType": "Storage.File.FileRangeWriteType", + "azure.storage.fileshare.models.FileLastWrittenMode": "Storage.File.FileLastWrittenMode", + "azure.storage.fileshare.models.FileRangeWriteFromUrlType": "Storage.File.FileRangeWriteFromUrlType", + "azure.storage.fileshare.models.PermissionCopyModeType": "Storage.File.PermissionCopyModeType", + "azure.storage.fileshare.models.ModeCopyMode": "Storage.File.ModeCopyMode", + "azure.storage.fileshare.models.OwnerCopyMode": "Storage.File.OwnerCopyMode", + "azure.storage.fileshare.models.LeaseStatusType": "Storage.File.LeaseStatusType", + "azure.storage.fileshare.models.LeaseStateType": "Storage.File.LeaseStateType", + "azure.storage.fileshare.models.LeaseDurationType": "Storage.File.LeaseDurationType", + "azure.storage.fileshare.models.ShareRootSquash": "Storage.File.ShareRootSquash", + "azure.storage.fileshare.models.ListSharesIncludeType": "Storage.File.ListSharesIncludeType", + "azure.storage.fileshare.models.ShareAccessTier": "Storage.File.ShareAccessTier", + "azure.storage.fileshare.models.DeleteSnapshotsOptionType": "Storage.File.DeleteSnapshotsOptionType", + "azure.storage.fileshare.operations.DirectoryOperations.create": "Storage.File.Directory.create", + "azure.storage.fileshare.aio.operations.DirectoryOperations.create": "Storage.File.Directory.create", + "azure.storage.fileshare.operations.DirectoryOperations.get_properties": "Storage.File.Directory.getProperties", + "azure.storage.fileshare.aio.operations.DirectoryOperations.get_properties": "Storage.File.Directory.getProperties", + "azure.storage.fileshare.operations.DirectoryOperations.delete": "Storage.File.Directory.delete", + "azure.storage.fileshare.aio.operations.DirectoryOperations.delete": "Storage.File.Directory.delete", + "azure.storage.fileshare.operations.DirectoryOperations.set_properties": "Storage.File.Directory.setProperties", + "azure.storage.fileshare.aio.operations.DirectoryOperations.set_properties": "Storage.File.Directory.setProperties", + "azure.storage.fileshare.operations.DirectoryOperations.set_metadata": "Storage.File.Directory.setMetadata", + "azure.storage.fileshare.aio.operations.DirectoryOperations.set_metadata": "Storage.File.Directory.setMetadata", + "azure.storage.fileshare.operations.DirectoryOperations.list_files_and_directories_segment": "Storage.File.Directory.listFilesAndDirectoriesSegment", + "azure.storage.fileshare.aio.operations.DirectoryOperations.list_files_and_directories_segment": "Storage.File.Directory.listFilesAndDirectoriesSegment", + "azure.storage.fileshare.operations.DirectoryOperations.list_handles": "Storage.File.Directory.listHandles", + "azure.storage.fileshare.aio.operations.DirectoryOperations.list_handles": "Storage.File.Directory.listHandles", + "azure.storage.fileshare.operations.DirectoryOperations.force_close_handles": "Storage.File.Directory.forceCloseHandles", + "azure.storage.fileshare.aio.operations.DirectoryOperations.force_close_handles": "Storage.File.Directory.forceCloseHandles", + "azure.storage.fileshare.operations.DirectoryOperations.rename": "Storage.File.Directory.rename", + "azure.storage.fileshare.aio.operations.DirectoryOperations.rename": "Storage.File.Directory.rename", + "azure.storage.fileshare.operations.FileOperations.create": "Storage.File.File.create", + "azure.storage.fileshare.aio.operations.FileOperations.create": "Storage.File.File.create", + "azure.storage.fileshare.operations.FileOperations.download": "Storage.File.File.download", + "azure.storage.fileshare.aio.operations.FileOperations.download": "Storage.File.File.download", + "azure.storage.fileshare.operations.FileOperations.get_properties": "Storage.File.File.getProperties", + "azure.storage.fileshare.aio.operations.FileOperations.get_properties": "Storage.File.File.getProperties", + "azure.storage.fileshare.operations.FileOperations.delete": "Storage.File.File.delete", + "azure.storage.fileshare.aio.operations.FileOperations.delete": "Storage.File.File.delete", + "azure.storage.fileshare.operations.FileOperations.set_http_headers": "Storage.File.File.setHttpHeaders", + "azure.storage.fileshare.aio.operations.FileOperations.set_http_headers": "Storage.File.File.setHttpHeaders", + "azure.storage.fileshare.operations.FileOperations.set_metadata": "Storage.File.File.setMetadata", + "azure.storage.fileshare.aio.operations.FileOperations.set_metadata": "Storage.File.File.setMetadata", + "azure.storage.fileshare.operations.FileOperations.acquire_lease": "Storage.File.File.acquireLease", + "azure.storage.fileshare.aio.operations.FileOperations.acquire_lease": "Storage.File.File.acquireLease", + "azure.storage.fileshare.operations.FileOperations.release_lease": "Storage.File.File.releaseLease", + "azure.storage.fileshare.aio.operations.FileOperations.release_lease": "Storage.File.File.releaseLease", + "azure.storage.fileshare.operations.FileOperations.change_lease": "Storage.File.File.changeLease", + "azure.storage.fileshare.aio.operations.FileOperations.change_lease": "Storage.File.File.changeLease", + "azure.storage.fileshare.operations.FileOperations.break_lease": "Storage.File.File.breakLease", + "azure.storage.fileshare.aio.operations.FileOperations.break_lease": "Storage.File.File.breakLease", + "azure.storage.fileshare.operations.FileOperations.upload_range": "Storage.File.File.uploadRange", + "azure.storage.fileshare.aio.operations.FileOperations.upload_range": "Storage.File.File.uploadRange", + "azure.storage.fileshare.operations.FileOperations.upload_range_from_url": "Storage.File.File.uploadRangeFromUrl", + "azure.storage.fileshare.aio.operations.FileOperations.upload_range_from_url": "Storage.File.File.uploadRangeFromUrl", + "azure.storage.fileshare.operations.FileOperations.get_range_list": "Storage.File.File.getRangeList", + "azure.storage.fileshare.aio.operations.FileOperations.get_range_list": "Storage.File.File.getRangeList", + "azure.storage.fileshare.operations.FileOperations.start_copy": "Storage.File.File.startCopy", + "azure.storage.fileshare.aio.operations.FileOperations.start_copy": "Storage.File.File.startCopy", + "azure.storage.fileshare.operations.FileOperations.abort_copy": "Storage.File.File.abortCopy", + "azure.storage.fileshare.aio.operations.FileOperations.abort_copy": "Storage.File.File.abortCopy", + "azure.storage.fileshare.operations.FileOperations.list_handles": "Storage.File.File.listHandles", + "azure.storage.fileshare.aio.operations.FileOperations.list_handles": "Storage.File.File.listHandles", + "azure.storage.fileshare.operations.FileOperations.force_close_handles": "Storage.File.File.forceCloseHandles", + "azure.storage.fileshare.aio.operations.FileOperations.force_close_handles": "Storage.File.File.forceCloseHandles", + "azure.storage.fileshare.operations.FileOperations.rename": "Storage.File.File.rename", + "azure.storage.fileshare.aio.operations.FileOperations.rename": "Storage.File.File.rename", + "azure.storage.fileshare.operations.FileOperations.create_symbolic_link": "Storage.File.File.createSymbolicLink", + "azure.storage.fileshare.aio.operations.FileOperations.create_symbolic_link": "Storage.File.File.createSymbolicLink", + "azure.storage.fileshare.operations.FileOperations.get_symbolic_link": "Storage.File.File.getSymbolicLink", + "azure.storage.fileshare.aio.operations.FileOperations.get_symbolic_link": "Storage.File.File.getSymbolicLink", + "azure.storage.fileshare.operations.FileOperations.create_hard_link": "Storage.File.File.createHardLink", + "azure.storage.fileshare.aio.operations.FileOperations.create_hard_link": "Storage.File.File.createHardLink", + "azure.storage.fileshare.operations.ServiceOperations.set_properties": "Storage.File.Service.setProperties", + "azure.storage.fileshare.aio.operations.ServiceOperations.set_properties": "Storage.File.Service.setProperties", + "azure.storage.fileshare.operations.ServiceOperations.get_properties": "Storage.File.Service.getProperties", + "azure.storage.fileshare.aio.operations.ServiceOperations.get_properties": "Storage.File.Service.getProperties", + "azure.storage.fileshare.operations.ServiceOperations.list_shares_segment": "Storage.File.Service.listSharesSegment", + "azure.storage.fileshare.aio.operations.ServiceOperations.list_shares_segment": "Storage.File.Service.listSharesSegment", + "azure.storage.fileshare.operations.ServiceOperations.get_user_delegation_key": "Storage.File.Service.getUserDelegationKey", + "azure.storage.fileshare.aio.operations.ServiceOperations.get_user_delegation_key": "Storage.File.Service.getUserDelegationKey", + "azure.storage.fileshare.operations.ShareOperations.create": "Storage.File.Share.create", + "azure.storage.fileshare.aio.operations.ShareOperations.create": "Storage.File.Share.create", + "azure.storage.fileshare.operations.ShareOperations.get_properties": "Storage.File.Share.getProperties", + "azure.storage.fileshare.aio.operations.ShareOperations.get_properties": "Storage.File.Share.getProperties", + "azure.storage.fileshare.operations.ShareOperations.delete": "Storage.File.Share.delete", + "azure.storage.fileshare.aio.operations.ShareOperations.delete": "Storage.File.Share.delete", + "azure.storage.fileshare.operations.ShareOperations.acquire_lease": "Storage.File.Share.acquireLease", + "azure.storage.fileshare.aio.operations.ShareOperations.acquire_lease": "Storage.File.Share.acquireLease", + "azure.storage.fileshare.operations.ShareOperations.release_lease": "Storage.File.Share.releaseLease", + "azure.storage.fileshare.aio.operations.ShareOperations.release_lease": "Storage.File.Share.releaseLease", + "azure.storage.fileshare.operations.ShareOperations.change_lease": "Storage.File.Share.changeLease", + "azure.storage.fileshare.aio.operations.ShareOperations.change_lease": "Storage.File.Share.changeLease", + "azure.storage.fileshare.operations.ShareOperations.renew_lease": "Storage.File.Share.renewLease", + "azure.storage.fileshare.aio.operations.ShareOperations.renew_lease": "Storage.File.Share.renewLease", + "azure.storage.fileshare.operations.ShareOperations.break_lease": "Storage.File.Share.breakLease", + "azure.storage.fileshare.aio.operations.ShareOperations.break_lease": "Storage.File.Share.breakLease", + "azure.storage.fileshare.operations.ShareOperations.create_snapshot": "Storage.File.Share.createSnapshot", + "azure.storage.fileshare.aio.operations.ShareOperations.create_snapshot": "Storage.File.Share.createSnapshot", + "azure.storage.fileshare.operations.ShareOperations.create_permission": "Storage.File.Share.createPermission", + "azure.storage.fileshare.aio.operations.ShareOperations.create_permission": "Storage.File.Share.createPermission", + "azure.storage.fileshare.operations.ShareOperations.get_permission": "Storage.File.Share.getPermission", + "azure.storage.fileshare.aio.operations.ShareOperations.get_permission": "Storage.File.Share.getPermission", + "azure.storage.fileshare.operations.ShareOperations.set_properties": "Storage.File.Share.setProperties", + "azure.storage.fileshare.aio.operations.ShareOperations.set_properties": "Storage.File.Share.setProperties", + "azure.storage.fileshare.operations.ShareOperations.set_metadata": "Storage.File.Share.setMetadata", + "azure.storage.fileshare.aio.operations.ShareOperations.set_metadata": "Storage.File.Share.setMetadata", + "azure.storage.fileshare.operations.ShareOperations.get_access_policy": "Storage.File.Share.getAccessPolicy", + "azure.storage.fileshare.aio.operations.ShareOperations.get_access_policy": "Storage.File.Share.getAccessPolicy", + "azure.storage.fileshare.operations.ShareOperations.set_access_policy": "Storage.File.Share.setAccessPolicy", + "azure.storage.fileshare.aio.operations.ShareOperations.set_access_policy": "Storage.File.Share.setAccessPolicy", + "azure.storage.fileshare.operations.ShareOperations.get_statistics": "Storage.File.Share.getStatistics", + "azure.storage.fileshare.aio.operations.ShareOperations.get_statistics": "Storage.File.Share.getStatistics", + "azure.storage.fileshare.operations.ShareOperations.restore": "Storage.File.Share.restore", + "azure.storage.fileshare.aio.operations.ShareOperations.restore": "Storage.File.Share.restore" + } +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-file-share/azure/__init__.py b/sdk/storage/azure-storage-file-share/azure/__init__.py index 0c36c2076ba0..d55ccad1f573 100644 --- a/sdk/storage/azure-storage-file-share/azure/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/__init__.py index 0c36c2076ba0..d55ccad1f573 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/__init__.py @@ -1 +1 @@ -__path__ = __import__('pkgutil').extend_path(__path__, __name__) # type: ignore +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/__init__.py index 660fa3798557..4b1cf17142a8 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/__init__.py @@ -42,52 +42,49 @@ ShareProtocolSettings, ShareProtocols, ) -from ._generated.models import ( - ShareAccessTier, - ShareRootSquash -) +from ._generated.models import ShareAccessTier, ShareRootSquash __version__ = VERSION __all__ = [ - 'AccessPolicy', - 'AccountSasPermissions', - 'ContentSettings', - 'CorsRule', - 'DirectoryProperties', - 'ExponentialRetry', - 'FileProperties', - 'FileSasPermissions', - 'generate_account_sas', - 'generate_file_sas', - 'generate_share_sas', - 'Handle', - 'LinearRetry', - 'LocationMode', - 'Metrics', - 'NfsEncryptionInTransit', - 'NTFSAttributes', - 'ResourceTypes', - 'RetentionPolicy', - 'Services', - 'ShareAccessTier', - 'ShareClient', - 'ShareDirectoryClient', - 'ShareFileClient', - 'ShareLeaseClient', - 'ShareNfsSettings', - 'ShareProperties', - 'ShareProtocolSettings', - 'ShareProtocols', - 'ShareRootSquash', - 'ShareSasPermissions', - 'ShareServiceClient', - 'ShareSmbSettings', - 'SmbEncryptionInTransit', - 'SmbMultichannel', - 'StorageErrorCode', - 'UserDelegationKey' + "AccessPolicy", + "AccountSasPermissions", + "ContentSettings", + "CorsRule", + "DirectoryProperties", + "ExponentialRetry", + "FileProperties", + "FileSasPermissions", + "generate_account_sas", + "generate_file_sas", + "generate_share_sas", + "Handle", + "LinearRetry", + "LocationMode", + "Metrics", + "NfsEncryptionInTransit", + "NTFSAttributes", + "ResourceTypes", + "RetentionPolicy", + "Services", + "ShareAccessTier", + "ShareClient", + "ShareDirectoryClient", + "ShareFileClient", + "ShareLeaseClient", + "ShareNfsSettings", + "ShareProperties", + "ShareProtocolSettings", + "ShareProtocols", + "ShareRootSquash", + "ShareSasPermissions", + "ShareServiceClient", + "ShareSmbSettings", + "SmbEncryptionInTransit", + "SmbMultichannel", + "StorageErrorCode", + "UserDelegationKey", ] @@ -96,12 +93,10 @@ # to prevent it from showing in intellisense/docs but we handle it here to prevent # breaking any existing code which may have imported it. def __getattr__(name): - if name == 'HandleItem': + if name == "HandleItem": from ._generated.models import HandleItem - warnings.warn( - "HandleItem is deprecated and should not be used. Use Handle instead.", - DeprecationWarning - ) + + warnings.warn("HandleItem is deprecated and should not be used. Use Handle instead.", DeprecationWarning) return HandleItem raise AttributeError(f"module 'azure.storage.fileshare' has no attribute {name}") diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_deserialize.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_deserialize.py index 5db600d5f5ed..a3adccf3cac7 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_deserialize.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_deserialize.py @@ -3,10 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------------_ -from typing import ( - Any, cast, Dict, List, Optional, Tuple, - TYPE_CHECKING -) +from typing import Any, cast, Dict, List, Optional, Tuple, TYPE_CHECKING from ._generated.models import ShareFileRangeList from ._models import DirectoryProperties, FileProperties, ShareProperties @@ -19,67 +16,89 @@ def deserialize_share_properties(response: "PipelineResponse", obj: Any, headers: Dict[str, Any]) -> ShareProperties: metadata = deserialize_metadata(response, obj, headers) - share_properties = ShareProperties( - metadata=metadata, - **headers - ) + share_properties = ShareProperties(metadata=metadata, **headers) return share_properties def deserialize_directory_properties( - response: "PipelineResponse", - obj: Any, - headers: Dict[str, Any] + response: "PipelineResponse", obj: Any, headers: Dict[str, Any] ) -> DirectoryProperties: metadata = deserialize_metadata(response, obj, headers) - directory_properties = DirectoryProperties( - metadata=metadata, - **headers - ) + directory_properties = DirectoryProperties(metadata=metadata, **headers) return directory_properties +class _StreamWrapper: + """Wraps a bytes iterator (sync or async) so that properties can be attached.""" + + def __init__(self, stream): + self._stream = stream + self.properties = None + self.response = None + + def __iter__(self): + return iter(self._stream) + + def __next__(self): + return next(self._stream) + + def __aiter__(self): + return self._stream.__aiter__() + + async def __anext__(self): + return await self._stream.__anext__() + + def deserialize_file_properties(response: "PipelineResponse", obj: Any, headers: Dict[str, Any]) -> FileProperties: metadata = deserialize_metadata(response, obj, headers) - file_properties = FileProperties( - metadata=metadata, - **headers - ) - if 'Content-Range' in headers: - if 'x-ms-content-md5' in headers: - file_properties.content_settings.content_md5 = headers['x-ms-content-md5'] + file_properties = FileProperties(metadata=metadata, **headers) + if "Content-Range" in headers: + if "x-ms-content-md5" in headers: + file_properties.content_settings.content_md5 = headers["x-ms-content-md5"] else: file_properties.content_settings.content_md5 = None return file_properties def deserialize_file_stream( - response: "PipelineResponse", - obj: Any, - headers: Dict[str, Any] + response: "PipelineResponse", obj: Any, headers: Dict[str, Any] ) -> Tuple["LocationMode", Any]: file_properties = deserialize_file_properties(response, obj, headers) + # The new TypeSpec-generated download returns an iterator (from iter_bytes/iter_raw) + # instead of a response object with settable attributes. Wrap it. + if not hasattr(obj, "properties") or isinstance(obj, type(iter(b""))): + wrapped = _StreamWrapper(obj) + wrapped.properties = file_properties + try: + wrapped.response = response.http_response + except AttributeError: + pass + return response.http_response.location_mode, wrapped obj.properties = file_properties return response.http_response.location_mode, obj # Extracts out file permission -def deserialize_permission(response: "PipelineResponse", obj: Any, headers: Dict[str, Any]) -> Optional[str]: # pylint: disable=unused-argument +def deserialize_permission( # pylint: disable=unused-argument + response: "PipelineResponse", obj: Any, headers: Dict[str, Any] +) -> Optional[str]: return cast(Optional[str], obj.permission) # Extracts out file permission key -def deserialize_permission_key(response: "PipelineResponse", obj: Any, headers: Dict[str, Any]) -> Optional[str]: # pylint: disable=unused-argument +def deserialize_permission_key( # pylint: disable=unused-argument + response: "PipelineResponse", obj: Any, headers: Dict[str, Any] +) -> Optional[str]: if response is None or headers is None: return None - return cast(Optional[str], headers.get('x-ms-file-permission-key', None)) + return cast(Optional[str], headers.get("x-ms-file-permission-key", None)) def get_file_ranges_result(ranges: ShareFileRangeList) -> Tuple[List[Dict[str, int]], List[Dict[str, int]]]: file_ranges = [] clear_ranges = [] if ranges.ranges: - file_ranges = [{'start': file_range.start, 'end': file_range.end} for file_range in ranges.ranges] + file_ranges = [{"start": file_range.start, "end": file_range.end} for file_range in ranges.ranges] if ranges.clear_ranges: - clear_ranges = [{'start': clear_range.start, 'end': clear_range.end} for clear_range in ranges.clear_ranges] + clear_ranges = [{"start": clear_range.start, "end": clear_range.end} for clear_range in ranges.clear_ranges] return file_ranges, clear_ranges diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_directory_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_directory_client.py index 5191ff9392ab..652f64ed4dce 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_directory_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_directory_client.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -9,10 +10,7 @@ import sys import time from datetime import datetime -from typing import ( - Any, AnyStr, cast, Dict, IO, Iterable, Optional, Union, - TYPE_CHECKING -) +from typing import Any, AnyStr, cast, Dict, IO, Iterable, Optional, Union, TYPE_CHECKING from typing_extensions import Self from azure.core.exceptions import HttpResponseError, ResourceNotFoundError @@ -20,15 +18,11 @@ from azure.core.pipeline import Pipeline from azure.core.tracing.decorator import distributed_trace from ._deserialize import deserialize_directory_properties -from ._directory_client_helpers import ( - _format_url, - _from_directory_url, - _parse_url -) +from ._directory_client_helpers import _format_url, _from_directory_url, _parse_url from ._file_client import ShareFileClient -from ._generated import AzureFileStorage +from ._generated import FileClient as AzureFileStorage from ._models import DirectoryPropertiesPaged, Handle, HandlesPaged -from ._parser import _datetime_to_str, _get_file_permission, _parse_snapshot +from ._parser import _datetime_to_str, _get_file_permission, _parse_snapshot, _strip_snapshot_from_url from ._serialize import get_api_version, get_dest_access_conditions, get_rename_smb_properties from ._shared.base_client import parse_connection_str, parse_query, StorageAccountHostsMixin, TransportWrapper from ._shared.request_handlers import add_metadata_headers @@ -103,42 +97,41 @@ class ShareDirectoryClient(StorageAccountHostsMixin): authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://.file.core.windows.net. """ + def __init__( - self, account_url: str, + self, + account_url: str, share_name: str, directory_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long *, - token_intent: Optional[Literal['backup']] = None, - **kwargs: Any + token_intent: Optional[Literal["backup"]] = None, + **kwargs: Any, ) -> None: - if hasattr(credential, 'get_token') and not token_intent: + if hasattr(credential, "get_token") and not token_intent: raise ValueError("'token_intent' keyword is required when 'credential' is an TokenCredential.") parsed_url = _parse_url(account_url, share_name) path_snapshot, sas_token = parse_query(parsed_url.query) if not sas_token and not credential: raise ValueError( - 'You need to provide either an account shared key or SAS token when creating a storage service.') + "You need to provide either an account shared key or SAS token when creating a storage service." + ) self.snapshot = _parse_snapshot(snapshot, path_snapshot) self.share_name = share_name self.directory_path = directory_path - self._query_str, credential = self._format_query_string( - sas_token, credential, share_snapshot=self.snapshot) - super(ShareDirectoryClient, self).__init__( - parsed_url, service='file-share', credential=credential, **kwargs) - self.allow_trailing_dot = kwargs.pop('allow_trailing_dot', None) - self.allow_source_trailing_dot = kwargs.pop('allow_source_trailing_dot', None) + self._query_str, credential = self._format_query_string(sas_token, credential, share_snapshot=self.snapshot) + super(ShareDirectoryClient, self).__init__(parsed_url, service="file-share", credential=credential, **kwargs) + self.allow_trailing_dot = kwargs.pop("allow_trailing_dot", None) + self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( + url=_strip_snapshot_from_url(self.url), version=get_api_version(kwargs), - url=self.url, - base_url=self.url, pipeline=self._pipeline, - allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, - file_request_intent=self.file_request_intent ) def __enter__(self) -> Self: @@ -159,10 +152,13 @@ def close(self) -> None: @classmethod def from_directory_url( - cls, directory_url: str, + cls, + directory_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """Create a ShareDirectoryClient from a directory url. @@ -193,8 +189,13 @@ def from_directory_url( """ account_url, share_name, directory_path, snapshot = _from_directory_url(directory_url, snapshot) return cls( - account_url=account_url, share_name=share_name, directory_path=directory_path, - snapshot=snapshot, credential=credential, **kwargs) + account_url=account_url, + share_name=share_name, + directory_path=directory_path, + snapshot=snapshot, + credential=credential, + **kwargs, + ) def _format_url(self, hostname: str) -> str: """Format the endpoint URL according to the current location mode hostname. @@ -208,11 +209,14 @@ def _format_url(self, hostname: str) -> str: @classmethod def from_connection_string( - cls, conn_str: str, + cls, + conn_str: str, share_name: str, directory_path: str, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """Create ShareDirectoryClient from a Connection String. @@ -239,11 +243,10 @@ def from_connection_string( :returns: A directory client. :rtype: ~azure.storage.fileshare.ShareDirectoryClient """ - account_url, secondary, credential = parse_connection_str(conn_str, credential, 'file') - if 'secondary_hostname' not in kwargs: - kwargs['secondary_hostname'] = secondary - return cls( - account_url, share_name=share_name, directory_path=directory_path, credential=credential, **kwargs) + account_url, secondary, credential = parse_connection_str(conn_str, credential, "file") + if "secondary_hostname" not in kwargs: + kwargs["secondary_hostname"] = secondary + return cls(account_url, share_name=share_name, directory_path=directory_path, credential=credential, **kwargs) def get_file_client(self, file_name: str, **kwargs: Any) -> ShareFileClient: """Get a client to interact with a specific file. @@ -255,19 +258,28 @@ def get_file_client(self, file_name: str, **kwargs: Any) -> ShareFileClient: :rtype: ~azure.storage.fileshare.ShareFileClient """ if self.directory_path: - file_name = self.directory_path.rstrip('/') + "/" + file_name + file_name = self.directory_path.rstrip("/") + "/" + file_name _pipeline = Pipeline( transport=TransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # pylint: disable=protected-access ) return ShareFileClient( - self.url, file_path=file_name, share_name=self.share_name, snapshot=self.snapshot, - credential=self.credential, token_intent=self.file_request_intent, api_version=self.api_version, - _hosts=self._hosts, _configuration=self._config, - _pipeline=_pipeline, _location_mode=self._location_mode, + self.url, + file_path=file_name, + share_name=self.share_name, + snapshot=self.snapshot, + credential=self.credential, + token_intent=self.file_request_intent, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, **kwargs) + allow_source_trailing_dot=self.allow_source_trailing_dot, + **kwargs, + ) def get_subdirectory_client(self, directory_name: str, **kwargs: Any) -> "ShareDirectoryClient": """Get a client to interact with a specific subdirectory. @@ -290,18 +302,28 @@ def get_subdirectory_client(self, directory_name: str, **kwargs: Any) -> "ShareD """ directory_path = directory_name if self.directory_path: - directory_path = self.directory_path.rstrip('/') + "/" + directory_name + directory_path = self.directory_path.rstrip("/") + "/" + directory_name _pipeline = Pipeline( transport=TransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # pylint: disable=protected-access ) return ShareDirectoryClient( - self.url, share_name=self.share_name, directory_path=directory_path, snapshot=self.snapshot, - credential=self.credential, token_intent=self.file_request_intent, api_version=self.api_version, - _hosts=self._hosts, _configuration=self._config, _pipeline=_pipeline, - _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, **kwargs) + self.url, + share_name=self.share_name, + directory_path=directory_path, + snapshot=self.snapshot, + credential=self.credential, + token_intent=self.file_request_intent, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + **kwargs, + ) @distributed_trace def create_directory(self, **kwargs: Any) -> Dict[str, Any]: @@ -374,31 +396,37 @@ def create_directory(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 12 :caption: Creates a directory. """ - timeout = kwargs.pop('timeout', None) - metadata = kwargs.pop('metadata', None) - headers = kwargs.pop('headers', {}) + timeout = kwargs.pop("timeout", None) + metadata = kwargs.pop("metadata", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) - file_attributes = kwargs.pop('file_attributes', None) - file_creation_time = kwargs.pop('file_creation_time', None) - file_last_write_time = kwargs.pop('file_last_write_time', None) - file_change_time = kwargs.pop('file_change_time', None) - file_permission = kwargs.pop('file_permission', None) - file_permission_key = kwargs.pop('file_permission_key', None) + file_attributes = kwargs.pop("file_attributes", None) + file_creation_time = kwargs.pop("file_creation_time", None) + file_last_write_time = kwargs.pop("file_last_write_time", None) + file_change_time = kwargs.pop("file_change_time", None) + file_permission = kwargs.pop("file_permission", None) + file_permission_key = kwargs.pop("file_permission_key", None) file_permission = _get_file_permission(file_permission, file_permission_key, None) try: - return cast(Dict[str, Any], self._client.directory.create( - file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - file_permission=file_permission, - file_permission_key=file_permission_key, - timeout=timeout, - cls=return_response_headers, - headers=headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.directory.create( + file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, + file_creation_time=_datetime_to_str(file_creation_time), + file_last_write_time=_datetime_to_str(file_last_write_time), + file_change_time=_datetime_to_str(file_change_time), + file_permission=file_permission, + file_permission_key=file_permission_key, + timeout=timeout, + cls=return_response_headers, + headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -424,9 +452,14 @@ def delete_directory(self, **kwargs: Any) -> None: :dedent: 12 :caption: Deletes a directory. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) try: - self._client.directory.delete(timeout=timeout, **kwargs) + self._client.directory.delete( + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) except HttpResponseError as error: process_storage_error(error) @@ -494,40 +527,51 @@ def rename_directory(self, new_name: str, **kwargs: Any) -> "ShareDirectoryClien if not new_name: raise ValueError("Please specify a new directory name.") - new_name = new_name.strip('/') - new_path_and_query = new_name.split('?') + new_name = new_name.strip("/") + new_path_and_query = new_name.split("?") new_dir_path = new_path_and_query[0] if len(new_path_and_query) == 2: - new_dir_sas = new_path_and_query[1] or self._query_str.strip('?') + new_dir_sas = new_path_and_query[1] or self._query_str.strip("?") else: - new_dir_sas = self._query_str.strip('?') + new_dir_sas = self._query_str.strip("?") new_directory_client = ShareDirectoryClient( - f'{self.scheme}://{self.primary_hostname}', self.share_name, new_dir_path, - credential=new_dir_sas or self.credential, api_version=self.api_version, - _hosts=self._hosts, _configuration=self._config, _pipeline=self._pipeline, - _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent + f"{self.scheme}://{self.primary_hostname}", + self.share_name, + new_dir_path, + credential=new_dir_sas or self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=self._pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, ) kwargs.update(get_rename_smb_properties(kwargs)) - timeout = kwargs.pop('timeout', None) - overwrite = kwargs.pop('overwrite', None) - metadata = kwargs.pop('metadata', None) - headers = kwargs.pop('headers', {}) + timeout = kwargs.pop("timeout", None) + overwrite = kwargs.pop("overwrite", None) + metadata = kwargs.pop("metadata", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) - destination_access_conditions = get_dest_access_conditions(kwargs.pop('destination_lease', None)) + destination_access_conditions = get_dest_access_conditions(kwargs.pop("destination_lease", None)) try: new_directory_client._client.directory.rename( # pylint: disable=protected-access - self.url, + rename_source=self.url, timeout=timeout, replace_if_exists=overwrite, - destination_lease_access_conditions=destination_access_conditions, + destination_lease_id=destination_access_conditions, headers=headers, - **kwargs) + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) return new_directory_client except HttpResponseError as error: @@ -535,9 +579,7 @@ def rename_directory(self, new_name: str, **kwargs: Any) -> "ShareDirectoryClien @distributed_trace def list_directories_and_files( - self, - name_starts_with: Optional[str] = None, - **kwargs: Any + self, name_starts_with: Optional[str] = None, **kwargs: Any ) -> ItemPaged[Union["DirectoryProperties", "FileProperties"]]: """Lists all the directories and files under the directory. @@ -577,16 +619,22 @@ def list_directories_and_files( :dedent: 12 :caption: List directories and files. """ - timeout = kwargs.pop('timeout', None) - results_per_page = kwargs.pop('results_per_page', None) + timeout = kwargs.pop("timeout", None) + results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( self._client.directory.list_files_and_directories_segment, sharesnapshot=self.snapshot, timeout=timeout, - **kwargs) + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) return ItemPaged( - command, prefix=name_starts_with, results_per_page=results_per_page, - page_iterator_class=DirectoryPropertiesPaged) + command, + prefix=name_starts_with, + results_per_page=results_per_page, + page_iterator_class=DirectoryPropertiesPaged, + ) @distributed_trace def list_handles(self, recursive: bool = False, **kwargs: Any) -> ItemPaged[Handle]: @@ -604,17 +652,18 @@ def list_handles(self, recursive: bool = False, **kwargs: Any) -> ItemPaged[Hand :returns: An auto-paging iterable of Handle :rtype: ~azure.core.paging.ItemPaged[~azure.storage.fileshare.Handle] """ - timeout = kwargs.pop('timeout', None) - results_per_page = kwargs.pop('results_per_page', None) + timeout = kwargs.pop("timeout", None) + results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( self._client.directory.list_handles, sharesnapshot=self.snapshot, timeout=timeout, recursive=recursive, - **kwargs) - return ItemPaged( - command, results_per_page=results_per_page, - page_iterator_class=HandlesPaged) + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) + return ItemPaged(command, results_per_page=results_per_page, page_iterator_class=HandlesPaged) @distributed_trace def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[str, int]: @@ -638,20 +687,22 @@ def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[str, i handle_id = handle.id else: handle_id = handle - if handle_id == '*': + if handle_id == "*": raise ValueError("Handle ID '*' is not supported. Use 'close_all_handles' instead.") try: response = self._client.directory.force_close_handles( - handle_id, + handle_id=handle_id, marker=None, recursive=None, sharesnapshot=self.snapshot, cls=return_response_headers, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) return { - 'closed_handles_count': response.get('number_of_handles_closed', 0), - 'failed_handles_count': response.get('number_of_handles_failed', 0) + "closed_handles_count": response.get("number_of_handles_closed", 0), + "failed_handles_count": response.get("number_of_handles_failed", 0), } except HttpResponseError as error: process_storage_error(error) @@ -675,7 +726,7 @@ def close_all_handles(self, recursive: bool = False, **kwargs: Any) -> Dict[str, and the number of handles failed to close in a dict. :rtype: dict[str, int] """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) start_time = time.time() try_close = True @@ -685,26 +736,25 @@ def close_all_handles(self, recursive: bool = False, **kwargs: Any) -> Dict[str, while try_close: try: response = self._client.directory.force_close_handles( - handle_id='*', + handle_id="*", timeout=timeout, marker=continuation_token, recursive=recursive, sharesnapshot=self.snapshot, cls=return_response_headers, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) except HttpResponseError as error: process_storage_error(error) - continuation_token = response.get('marker') + continuation_token = response.get("marker") try_close = bool(continuation_token) - total_closed += response.get('number_of_handles_closed', 0) - total_failed += response.get('number_of_handles_failed', 0) + total_closed += response.get("number_of_handles_closed", 0) + total_failed += response.get("number_of_handles_failed", 0) if timeout: timeout = max(0, timeout - (time.time() - start_time)) - return { - 'closed_handles_count': total_closed, - 'failed_handles_count': total_failed - } + return {"closed_handles_count": total_closed, "failed_handles_count": total_failed} @distributed_trace def get_directory_properties(self, **kwargs: Any) -> "DirectoryProperties": @@ -721,12 +771,19 @@ def get_directory_properties(self, **kwargs: Any) -> "DirectoryProperties": :returns: DirectoryProperties :rtype: ~azure.storage.fileshare.DirectoryProperties """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) try: - response = cast("DirectoryProperties", self._client.directory.get_properties( - timeout=timeout, - cls=deserialize_directory_properties, - **kwargs)) + response = cast( + "DirectoryProperties", + self._client.directory.get_properties( + timeout=timeout, + cls=deserialize_directory_properties, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + sharesnapshot=self.snapshot, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) return response @@ -751,15 +808,21 @@ def set_directory_metadata(self, metadata: Dict[str, Any], **kwargs: Any) -> Dic :returns: Directory-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], self._client.directory.set_metadata( - timeout=timeout, - cls=return_response_headers, - headers=headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.directory.set_metadata( + timeout=timeout, + cls=return_response_headers, + headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -778,7 +841,12 @@ def exists(self, **kwargs: Any) -> bool: :rtype: bool """ try: - self._client.directory.get_properties(**kwargs) + self._client.directory.get_properties( + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + sharesnapshot=self.snapshot, + **kwargs, + ) return True except HttpResponseError as error: try: @@ -788,12 +856,13 @@ def exists(self, **kwargs: Any) -> bool: @distributed_trace def set_http_headers( - self, file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, + self, + file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, file_creation_time: Optional[Union[str, datetime]] = None, file_last_write_time: Optional[Union[str, datetime]] = None, file_permission: Optional[str] = None, permission_key: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """Sets HTTP headers on the directory. @@ -843,20 +912,26 @@ def set_http_headers( :returns: File-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) file_permission = _get_file_permission(file_permission, permission_key, None) - file_change_time = kwargs.pop('file_change_time', None) + file_change_time = kwargs.pop("file_change_time", None) try: - return cast(Dict[str, Any], self._client.directory.set_properties( - file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - file_permission=file_permission, - file_permission_key=permission_key, - timeout=timeout, - cls=return_response_headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.directory.set_properties( + file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, + file_creation_time=_datetime_to_str(file_creation_time), + file_last_write_time=_datetime_to_str(file_last_write_time), + file_change_time=_datetime_to_str(file_change_time), + file_permission=file_permission, + file_permission_key=permission_key, + timeout=timeout, + cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -888,8 +963,8 @@ def create_subdirectory(self, directory_name: str, **kwargs: Any) -> "ShareDirec :dedent: 12 :caption: Create a subdirectory. """ - metadata = kwargs.pop('metadata', None) - timeout = kwargs.pop('timeout', None) + metadata = kwargs.pop("metadata", None) + timeout = kwargs.pop("timeout", None) subdir = self.get_subdirectory_client(directory_name) subdir.create_directory(metadata=metadata, timeout=timeout, **kwargs) return subdir @@ -917,16 +992,17 @@ def delete_subdirectory(self, directory_name: str, **kwargs: Any) -> None: :dedent: 12 :caption: Delete a subdirectory. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) subdir = self.get_subdirectory_client(directory_name) subdir.delete_directory(timeout=timeout, **kwargs) @distributed_trace def upload_file( - self, file_name: str, + self, + file_name: str, data: Union[bytes, str, Iterable[AnyStr], IO[AnyStr]], length: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> ShareFileClient: """Creates a new file in the directory and returns a ShareFileClient to interact with the file. @@ -979,10 +1055,7 @@ def upload_file( :caption: Upload a file to a directory. """ file_client = self.get_file_client(file_name) - file_client.upload_file( - data, - length=length, - **kwargs) + file_client.upload_file(data, length=length, **kwargs) return file_client @distributed_trace diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_directory_client_helpers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_directory_client_helpers.py index cf37c24f02e1..4f05e151ffc9 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_directory_client_helpers.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_directory_client_helpers.py @@ -4,10 +4,7 @@ # license information. # -------------------------------------------------------------------------- -from typing import ( - Any, Dict, Optional, Tuple, Union, - TYPE_CHECKING -) +from typing import Any, Dict, Optional, Tuple, Union, TYPE_CHECKING from urllib.parse import quote, unquote, urlparse from ._shared.base_client import parse_query @@ -18,11 +15,11 @@ def _parse_url(account_url: str, share_name: str) -> "ParseResult": try: - if not account_url.lower().startswith('http'): + if not account_url.lower().startswith("http"): account_url = "https://" + account_url except AttributeError as exc: raise ValueError("Account URL must be a string.") from exc - parsed_url = urlparse(account_url.rstrip('/')) + parsed_url = urlparse(account_url.rstrip("/")) if not share_name: raise ValueError("Please specify a share name.") if not parsed_url.netloc: @@ -32,29 +29,28 @@ def _parse_url(account_url: str, share_name: str) -> "ParseResult": def _format_url(scheme: str, hostname: str, share_name: Union[str, bytes], dir_path: str, query_str: str) -> str: if isinstance(share_name, str): - share_name = share_name.encode('UTF-8') + share_name = share_name.encode("UTF-8") directory_path = "" if dir_path: - directory_path = "/" + quote(dir_path, safe='~') + directory_path = "/" + quote(dir_path, safe="~") return f"{scheme}://{hostname}/{quote(share_name)}{directory_path}{query_str}" def _from_directory_url( - directory_url: str, - snapshot: Optional[Union[str, Dict[str, Any]]] = None + directory_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None ) -> Tuple[str, str, str, Optional[Union[str, Dict[str, Any]]]]: try: - if not directory_url.lower().startswith('http'): + if not directory_url.lower().startswith("http"): directory_url = "https://" + directory_url except AttributeError as exc: raise ValueError("Directory URL must be a string.") from exc - parsed_url = urlparse(directory_url.rstrip('/')) + parsed_url = urlparse(directory_url.rstrip("/")) if not parsed_url.path and not parsed_url.netloc: raise ValueError(f"Invalid URL: {directory_url}") - account_url = parsed_url.netloc.rstrip('/') + "?" + parsed_url.query + account_url = parsed_url.netloc.rstrip("/") + "?" + parsed_url.query path_snapshot, _ = parse_query(parsed_url.query) - share_name, _, path_dir = parsed_url.path.lstrip('/').partition('/') + share_name, _, path_dir = parsed_url.path.lstrip("/").partition("/") share_name = unquote(share_name) snapshot = snapshot or path_snapshot diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_download.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_download.py index 935b17ebfde9..7611d8483b61 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_download.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_download.py @@ -8,10 +8,7 @@ import threading import warnings from io import BytesIO -from typing import ( - Any, Callable, Generator, IO, Iterator, Optional, Tuple, - TYPE_CHECKING -) +from typing import Any, Callable, Generator, IO, Iterator, Optional, Tuple, TYPE_CHECKING from azure.core.exceptions import HttpResponseError, ResourceModifiedError from azure.core.tracing.common import with_current_context @@ -37,7 +34,8 @@ def process_content(data: Any) -> bytes: class _ChunkDownloader: # pylint: disable=too-many-instance-attributes def __init__( - self, client: "FileOperations", + self, + client: "FileOperations", total_size: int, chunk_size: int, current_progress: int, @@ -48,7 +46,7 @@ def __init__( stream: Any = None, parallel: Optional[int] = None, progress_hook: Optional[Callable[[int, Optional[int]], None]] = None, - **kwargs: Any + **kwargs: Any, ) -> None: self.client = client self.etag = etag @@ -131,7 +129,7 @@ def _download_chunk(self, chunk_start: int, chunk_end: int) -> bytes: validate_content=self.validate_content, data_stream_total=self.total_size, download_stream_current=self.progress_total, - **self.request_options + **self.request_options, ) if response.properties.etag != self.etag: raise ResourceModifiedError(message="The file has been modified while downloading.") @@ -192,7 +190,7 @@ def __next__(self) -> bytes: def _get_chunk_data(self) -> bytes: chunk_data = self._current_content[: self._chunk_size] - self._current_content = self._current_content[self._chunk_size:] + self._current_content = self._current_content[self._chunk_size :] return chunk_data @@ -213,7 +211,8 @@ class StorageStreamDownloader: # pylint: disable=too-many-instance-attributes otherwise the total size of the file.""" def __init__( - self, client: "FileOperations" = None, # type: ignore [assignment] + self, + client: "FileOperations" = None, # type: ignore [assignment] config: "StorageConfiguration" = None, # type: ignore [assignment] start_range: Optional[int] = None, end_range: Optional[int] = None, @@ -223,7 +222,7 @@ def __init__( path: str = None, # type: ignore [assignment] share: str = None, # type: ignore [assignment] encoding: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> None: self.name = name self.path = path @@ -237,7 +236,7 @@ def __init__( self._max_concurrency = max_concurrency if max_concurrency is not None else DEFAULT_MAX_CONCURRENCY self._encoding = encoding self._validate_content = validate_content - self._progress_hook = kwargs.pop('progress_hook', None) + self._progress_hook = kwargs.pop("progress_hook", None) self._request_options = kwargs self._location_mode = None self._download_complete = False @@ -292,7 +291,7 @@ def _initial_request(self): self._initial_range[1], start_range_required=False, end_range_required=False, - check_content_md5=self._validate_content + check_content_md5=self._validate_content, ) try: @@ -302,7 +301,7 @@ def _initial_request(self): validate_content=self._validate_content, data_stream_total=None, download_stream_current=0, - **self._request_options + **self._request_options, ) # Check the location we read from to ensure we use the same one @@ -333,7 +332,7 @@ def _initial_request(self): validate_content=self._validate_content, data_stream_total=0, download_stream_current=0, - **self._request_options + **self._request_options, ) except HttpResponseError as e: process_storage_error(e) @@ -377,13 +376,14 @@ def chunks(self) -> Iterator[bytes]: validate_content=self._validate_content, use_location=self._location_mode, etag=self._etag, - **self._request_options + **self._request_options, ) return _ChunkIterator( size=self.size, content=self._current_content, downloader=iter_downloader, - chunk_size=self._config.max_chunk_get_size) + chunk_size=self._config.max_chunk_get_size, + ) def readall(self) -> bytes: """Download the contents of this file. @@ -411,10 +411,7 @@ def content_as_bytes(self, max_concurrency=None): :return: The contents of the file as bytes. :rtype: bytes """ - warnings.warn( - "content_as_bytes is deprecated, use readall instead", - DeprecationWarning - ) + warnings.warn("content_as_bytes is deprecated, use readall instead", DeprecationWarning) self._max_concurrency = max_concurrency if max_concurrency is not None else DEFAULT_MAX_CONCURRENCY return self.readall() @@ -432,10 +429,7 @@ def content_as_text(self, max_concurrency=None, encoding="UTF-8"): :return: The contents of the file as a str. :rtype: str """ - warnings.warn( - "content_as_text is deprecated, use readall instead", - DeprecationWarning - ) + warnings.warn("content_as_text is deprecated, use readall instead", DeprecationWarning) self._max_concurrency = max_concurrency if max_concurrency is not None else DEFAULT_MAX_CONCURRENCY self._encoding = encoding return self.readall() @@ -488,15 +482,13 @@ def readinto(self, stream: IO[bytes]) -> int: use_location=self._location_mode, progress_hook=self._progress_hook, etag=self._etag, - **self._request_options + **self._request_options, ) if parallel: import concurrent.futures + with concurrent.futures.ThreadPoolExecutor(self._max_concurrency) as executor: - list(executor.map( - with_current_context(downloader.process_chunk), - downloader.get_chunk_offsets() - )) + list(executor.map(with_current_context(downloader.process_chunk), downloader.get_chunk_offsets())) else: for chunk in downloader.get_chunk_offsets(): downloader.process_chunk(chunk) @@ -516,10 +508,7 @@ def download_to_stream(self, stream, max_concurrency=None): :returns: The properties of the downloaded file. :rtype: Any """ - warnings.warn( - "download_to_stream is deprecated, use readinto instead", - DeprecationWarning - ) + warnings.warn("download_to_stream is deprecated, use readinto instead", DeprecationWarning) self._max_concurrency = max_concurrency if max_concurrency is not None else DEFAULT_MAX_CONCURRENCY self.readinto(stream) return self.properties diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client.py index 78bfa03a6945..9ef05f471b16 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -9,10 +10,7 @@ import time from datetime import datetime from io import BytesIO -from typing import ( - Any, AnyStr, Callable, cast, Dict, IO, Iterable, List, Literal, Optional, Tuple, Union, - TYPE_CHECKING -) +from typing import Any, AnyStr, Callable, cast, Dict, IO, Iterable, List, Literal, Optional, Tuple, Union, TYPE_CHECKING from typing_extensions import Self from azure.core.exceptions import HttpResponseError, ResourceNotFoundError @@ -25,20 +23,19 @@ _from_file_url, _get_ranges_options, _parse_url, - _upload_range_from_url_options + _upload_range_from_url_options, ) -from ._generated import AzureFileStorage -from ._generated.models import FileHTTPHeaders +from ._generated import FileClient as AzureFileStorage from ._lease import ShareLeaseClient from ._models import FileProperties, Handle, HandlesPaged -from ._parser import _datetime_to_str, _get_file_permission, _parse_snapshot +from ._parser import _datetime_to_str, _get_file_permission, _parse_snapshot, _strip_snapshot_from_url from ._serialize import ( get_access_conditions, get_api_version, get_dest_access_conditions, get_rename_smb_properties, get_smb_properties, - get_source_access_conditions + get_source_access_conditions, ) from ._shared.base_client import StorageAccountHostsMixin, parse_connection_str, parse_query from ._shared.constants import DEFAULT_MAX_CONCURRENCY @@ -68,7 +65,7 @@ def _upload_file_helper( file_permission: Optional[str] = None, file_permission_key: Optional[str] = None, progress_hook: Optional[Callable[[int, Optional[int]], None]] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: try: if size is None or size < 0: @@ -83,7 +80,7 @@ def _upload_file_helper( file_last_write_time=file_last_write_time, file_permission=file_permission, permission_key=file_permission_key, - **kwargs + **kwargs, ) if size == 0: return response @@ -98,9 +95,9 @@ def _upload_file_helper( validate_content=validate_content, progress_hook=progress_hook, timeout=timeout, - **kwargs + **kwargs, ) - return cast(Dict[str, Any], sorted(responses, key=lambda r: r.get('last_modified'))[-1]) + return cast(Dict[str, Any], sorted(responses, key=lambda r: r.get("last_modified"))[-1]) except HttpResponseError as error: process_storage_error(error) @@ -161,44 +158,43 @@ class ShareFileClient(StorageAccountHostsMixin): authentication. Only has an effect when credential is of type TokenCredential. The value could be https://storage.azure.com/ (default) or https://.file.core.windows.net. """ + def __init__( - self, account_url: str, + self, + account_url: str, share_name: str, file_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long *, - token_intent: Optional[Literal['backup']] = None, - **kwargs: Any + token_intent: Optional[Literal["backup"]] = None, + **kwargs: Any, ) -> None: - if hasattr(credential, 'get_token') and not token_intent: + if hasattr(credential, "get_token") and not token_intent: raise ValueError("'token_intent' keyword is required when 'credential' is an TokenCredential.") parsed_url = _parse_url(account_url, share_name, file_path) path_snapshot, sas_token = parse_query(parsed_url.query) if not sas_token and not credential: raise ValueError( - 'You need to provide either an account shared key or SAS token when creating a storage service.') + "You need to provide either an account shared key or SAS token when creating a storage service." + ) self.snapshot = _parse_snapshot(snapshot, path_snapshot) self.share_name = share_name - self.file_path = file_path.split('/') + self.file_path = file_path.split("/") self.file_name = self.file_path[-1] self.directory_path = "/".join(self.file_path[:-1]) - self._query_str, credential = self._format_query_string( - sas_token, credential, share_snapshot=self.snapshot) - super(ShareFileClient, self).__init__( - parsed_url, service='file-share', credential=credential, **kwargs) - self.allow_trailing_dot = kwargs.pop('allow_trailing_dot', None) - self.allow_source_trailing_dot = kwargs.pop('allow_source_trailing_dot', None) + self._query_str, credential = self._format_query_string(sas_token, credential, share_snapshot=self.snapshot) + super(ShareFileClient, self).__init__(parsed_url, service="file-share", credential=credential, **kwargs) + self.allow_trailing_dot = kwargs.pop("allow_trailing_dot", None) + self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( + url=_strip_snapshot_from_url(self.url), version=get_api_version(kwargs), - url=self.url, - base_url=self.url, pipeline=self._pipeline, - allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, - file_request_intent=self.file_request_intent ) def __enter__(self) -> Self: @@ -219,10 +215,13 @@ def close(self) -> None: @classmethod def from_file_url( - cls, file_url: str, + cls, + file_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """A client to interact with a specific file, although that file may not yet exist. @@ -258,12 +257,15 @@ def _format_url(self, hostname: str): @classmethod def from_connection_string( - cls, conn_str: str, + cls, + conn_str: str, share_name: str, file_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """Create ShareFileClient from a Connection String. @@ -305,11 +307,12 @@ def from_connection_string( :dedent: 12 :caption: Creates the file client with connection string. """ - account_url, secondary, credential = parse_connection_str(conn_str, credential, 'file') - if 'secondary_hostname' not in kwargs: - kwargs['secondary_hostname'] = secondary + account_url, secondary, credential = parse_connection_str(conn_str, credential, "file") + if "secondary_hostname" not in kwargs: + kwargs["secondary_hostname"] = secondary return cls( - account_url, share_name=share_name, file_path=file_path, snapshot=snapshot, credential=credential, **kwargs) + account_url, share_name=share_name, file_path=file_path, snapshot=snapshot, credential=credential, **kwargs + ) @distributed_trace def acquire_lease(self, lease_id: Optional[str] = None, **kwargs: Any) -> ShareLeaseClient: @@ -340,7 +343,7 @@ def acquire_lease(self, lease_id: Optional[str] = None, **kwargs: Any) -> ShareL :dedent: 12 :caption: Acquiring a lease on a file. """ - kwargs['lease_duration'] = -1 + kwargs["lease_duration"] = -1 lease = ShareLeaseClient(self, lease_id=lease_id) lease.acquire(**kwargs) return lease @@ -360,7 +363,12 @@ def exists(self, **kwargs: Any) -> bool: :rtype: bool """ try: - self._client.file.get_properties(**kwargs) + self._client.file.get_properties( + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + sharesnapshot=self.snapshot, + **kwargs, + ) return True except HttpResponseError as error: try: @@ -370,13 +378,14 @@ def exists(self, **kwargs: Any) -> bool: @distributed_trace def create_file( - self, size: int, + self, + size: int, file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, file_creation_time: Optional[Union[str, datetime]] = None, file_last_write_time: Optional[Union[str, datetime]] = None, file_permission: Optional[str] = None, permission_key: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """Creates a new file. @@ -467,56 +476,63 @@ def create_file( :dedent: 12 :caption: Create a file. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - content_settings = kwargs.pop('content_settings', None) - metadata = kwargs.pop('metadata', None) - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + content_settings = kwargs.pop("content_settings", None) + metadata = kwargs.pop("metadata", None) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) - data = kwargs.pop('data', None) - file_http_headers = None + data = kwargs.pop("data", None) + file_http_headers = {} if content_settings: - file_http_headers = FileHTTPHeaders( - file_cache_control=content_settings.cache_control, - file_content_type=content_settings.content_type, - file_content_md5=bytearray(content_settings.content_md5) if content_settings.content_md5 else None, - file_content_encoding=content_settings.content_encoding, - file_content_language=content_settings.content_language, - file_content_disposition=content_settings.content_disposition - ) + file_http_headers = { + "file_cache_control": content_settings.cache_control, + "file_content_type": content_settings.content_type, + "file_content_md5": bytearray(content_settings.content_md5) if content_settings.content_md5 else None, + "file_content_encoding": content_settings.content_encoding, + "file_content_language": content_settings.content_language, + "file_content_disposition": content_settings.content_disposition, + } file_permission = _get_file_permission(file_permission, permission_key, None) - file_change_time = kwargs.pop('file_change_time', None) + file_change_time = kwargs.pop("file_change_time", None) try: - return cast(Dict[str, Any], self._client.file.create( - file_content_length=size, - metadata=metadata, - file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - file_permission=file_permission, - file_permission_key=permission_key, - file_http_headers=file_http_headers, - optionalbody=data, - content_length=len(data) if data is not None else None, - lease_access_conditions=access_conditions, - headers=headers, - timeout=timeout, - cls=return_response_headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.file.create( + file_content_length=size, + metadata=metadata, + file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, + file_creation_time=_datetime_to_str(file_creation_time), + file_last_write_time=_datetime_to_str(file_last_write_time), + file_change_time=_datetime_to_str(file_change_time), + file_permission=file_permission, + file_permission_key=permission_key, + **file_http_headers, + optional_body=data, + content_length=len(data) if data is not None else None, + lease_id=access_conditions, + headers=headers, + timeout=timeout, + cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace def upload_file( - self, data: Union[bytes, str, Iterable[AnyStr], IO[bytes]], + self, + data: Union[bytes, str, Iterable[AnyStr], IO[bytes]], length: Optional[int] = None, file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, file_creation_time: Optional[Union[str, datetime]] = None, file_last_write_time: Optional[Union[str, datetime]] = None, file_permission: Optional[str] = None, permission_key: Optional[str] = None, - **kwargs + **kwargs, ) -> Dict[str, Any]: """Uploads a new file. @@ -605,15 +621,15 @@ def upload_file( :dedent: 12 :caption: Upload a file. """ - metadata = kwargs.pop('metadata', None) - content_settings = kwargs.pop('content_settings', None) - max_concurrency = kwargs.pop('max_concurrency', None) + metadata = kwargs.pop("metadata", None) + content_settings = kwargs.pop("content_settings", None) + max_concurrency = kwargs.pop("max_concurrency", None) if max_concurrency is None: max_concurrency = DEFAULT_MAX_CONCURRENCY - validate_content = kwargs.pop('validate_content', False) - progress_hook = kwargs.pop('progress_hook', None) - timeout = kwargs.pop('timeout', None) - encoding = kwargs.pop('encoding', 'UTF-8') + validate_content = kwargs.pop("validate_content", False) + progress_hook = kwargs.pop("progress_hook", None) + timeout = kwargs.pop("timeout", None) + encoding = kwargs.pop("encoding", "UTF-8") if isinstance(data, str): data = data.encode(encoding) @@ -625,9 +641,9 @@ def upload_file( stream: Optional[Any] = None if isinstance(data, bytes): stream = BytesIO(data) - elif hasattr(data, 'read'): + elif hasattr(data, "read"): stream = data - elif hasattr(data, '__iter__'): + elif hasattr(data, "__iter__"): stream = IterStreamer(data, encoding=encoding) else: raise TypeError(f"Unsupported data type: {type(data)}") @@ -647,7 +663,8 @@ def upload_file( file_permission=file_permission, file_permission_key=permission_key, progress_hook=progress_hook, - **kwargs) + **kwargs, + ) @distributed_trace def start_copy_from_url(self, source_url: str, **kwargs: Any) -> Dict[str, Any]: @@ -789,31 +806,38 @@ def start_copy_from_url(self, source_url: str, **kwargs: Any) -> Dict[str, Any]: :dedent: 12 :caption: Copy a file from a URL """ - metadata = kwargs.pop('metadata', None) - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) - owner = kwargs.pop('owner', None) - group = kwargs.pop('group', None) - file_mode = kwargs.pop('file_mode', None) - file_mode_copy_mode = kwargs.pop('file_mode_copy_mode', None) - file_owner_copy_mode = kwargs.pop('owner_copy_mode', None) - headers = kwargs.pop('headers', {}) + metadata = kwargs.pop("metadata", None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) + owner = kwargs.pop("owner", None) + group = kwargs.pop("group", None) + file_mode = kwargs.pop("file_mode", None) + file_mode_copy_mode = kwargs.pop("file_mode_copy_mode", None) + file_owner_copy_mode = kwargs.pop("owner_copy_mode", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) kwargs.update(get_smb_properties(kwargs)) try: - return cast(Dict[str, Any], self._client.file.start_copy( - source_url, - metadata=metadata, - lease_access_conditions=access_conditions, - owner=owner, - group=group, - file_mode=file_mode, - file_mode_copy_mode=file_mode_copy_mode, - file_owner_copy_mode=file_owner_copy_mode, - headers=headers, - cls=return_response_headers, - timeout=timeout, - **kwargs)) + return cast( + Dict[str, Any], + self._client.file.start_copy( + copy_source=source_url, + metadata=metadata, + lease_id=access_conditions, + owner=owner, + group=group, + file_mode=file_mode, + file_mode_copy_mode=file_mode_copy_mode, + file_owner_copy_mode=file_owner_copy_mode, + headers=headers, + cls=return_response_headers, + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -843,25 +867,28 @@ def abort_copy(self, copy_id: Union[str, FileProperties], **kwargs: Any) -> None #other-client--per-operation-configuration>`__. :rtype: None """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) if isinstance(copy_id, FileProperties): copy_id = copy_id.copy.id elif isinstance(copy_id, Dict): - copy_id = copy_id['copy_id'] + copy_id = copy_id["copy_id"] try: - self._client.file.abort_copy(copy_id=copy_id, - lease_access_conditions=access_conditions, - timeout=timeout, **kwargs) + self._client.file.abort_copy( + copyid=copy_id, + lease_id=access_conditions, + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace def download_file( - self, offset: Optional[int] = None, - length: Optional[int] = None, - **kwargs: Any + self, offset: Optional[int] = None, length: Optional[int] = None, **kwargs: Any ) -> StorageStreamDownloader: """Downloads a file to the StorageStreamDownloader. The readall() method must be used to read all the content or readinto() must be used to download the file into @@ -924,7 +951,13 @@ def download_file( raise ValueError("Offset value must not be None if length is set.") range_end = offset + length - 1 # Service actually uses an end-range inclusive index - access_conditions = get_access_conditions(kwargs.pop('lease', None)) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + + # download doesn't accept sharesnapshot as a kwarg, inject via params + if self.snapshot: + params = kwargs.pop("params", {}) or {} + params["sharesnapshot"] = self.snapshot + kwargs["params"] = params return StorageStreamDownloader( client=self._client.file, @@ -932,11 +965,14 @@ def download_file( start_range=offset, end_range=range_end, name=self.file_name, - path='/'.join(self.file_path), + path="/".join(self.file_path), share=self.share_name, - lease_access_conditions=access_conditions, + lease_id=access_conditions, cls=deserialize_file_stream, - **kwargs) + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) @distributed_trace def delete_file(self, **kwargs: Any) -> None: @@ -967,10 +1003,16 @@ def delete_file(self, **kwargs: Any) -> None: :dedent: 12 :caption: Delete a file. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - self._client.file.delete(lease_access_conditions=access_conditions, timeout=timeout, **kwargs) + self._client.file.delete( + lease_id=access_conditions, + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) except HttpResponseError as error: process_storage_error(error) @@ -1049,50 +1091,56 @@ def rename_file(self, new_name: str, **kwargs: Any) -> "ShareFileClient": if not new_name: raise ValueError("Please specify a new file name.") - new_name = new_name.strip('/') - new_path_and_query = new_name.split('?') + new_name = new_name.strip("/") + new_path_and_query = new_name.split("?") new_file_path = new_path_and_query[0] if len(new_path_and_query) == 2: - new_file_sas = new_path_and_query[1] or self._query_str.strip('?') + new_file_sas = new_path_and_query[1] or self._query_str.strip("?") else: - new_file_sas = self._query_str.strip('?') + new_file_sas = self._query_str.strip("?") new_file_client = ShareFileClient( - f'{self.scheme}://{self.primary_hostname}', self.share_name, new_file_path, - credential=new_file_sas or self.credential, api_version=self.api_version, - _hosts=self._hosts, _configuration=self._config, _pipeline=self._pipeline, - _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent + f"{self.scheme}://{self.primary_hostname}", + self.share_name, + new_file_path, + credential=new_file_sas or self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=self._pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, ) kwargs.update(get_rename_smb_properties(kwargs)) - file_http_headers = None - content_type = kwargs.pop('content_type', None) - if content_type: - file_http_headers = FileHTTPHeaders( - file_content_type=content_type - ) + file_content_type = kwargs.pop("content_type", None) - timeout = kwargs.pop('timeout', None) - overwrite = kwargs.pop('overwrite', None) - metadata = kwargs.pop('metadata', None) - headers = kwargs.pop('headers', {}) + timeout = kwargs.pop("timeout", None) + overwrite = kwargs.pop("overwrite", None) + metadata = kwargs.pop("metadata", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) - source_access_conditions = get_source_access_conditions(kwargs.pop('source_lease', None)) - dest_access_conditions = get_dest_access_conditions(kwargs.pop('destination_lease', None)) + source_access_conditions = get_source_access_conditions(kwargs.pop("source_lease", None)) + dest_access_conditions = get_dest_access_conditions(kwargs.pop("destination_lease", None)) try: new_file_client._client.file.rename( # pylint: disable=protected-access - self.url, + rename_source=self.url, timeout=timeout, replace_if_exists=overwrite, - file_http_headers=file_http_headers, - source_lease_access_conditions=source_access_conditions, - destination_lease_access_conditions=dest_access_conditions, + file_content_type=file_content_type, + source_lease_id=source_access_conditions, + destination_lease_id=dest_access_conditions, headers=headers, - **kwargs) + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) return new_file_client except HttpResponseError as error: @@ -1119,32 +1167,39 @@ def get_file_properties(self, **kwargs: Any) -> FileProperties: :returns: FileProperties :rtype: ~azure.storage.fileshare.FileProperties """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - file_props = cast(FileProperties, self._client.file.get_properties( - sharesnapshot=self.snapshot, - lease_access_conditions=access_conditions, - timeout=timeout, - cls=deserialize_file_properties, - **kwargs)) + file_props = cast( + FileProperties, + self._client.file.get_properties( + sharesnapshot=self.snapshot, + lease_id=access_conditions, + timeout=timeout, + cls=deserialize_file_properties, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) file_props.name = self.file_name file_props.share = self.share_name file_props.snapshot = self.snapshot - file_props.path = '/'.join(self.file_path) + file_props.path = "/".join(self.file_path) return file_props @distributed_trace def set_http_headers( - self, content_settings: "ContentSettings", + self, + content_settings: "ContentSettings", file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, file_creation_time: Optional[Union[str, datetime]] = None, file_last_write_time: Optional[Union[str, datetime]] = None, file_permission: Optional[str] = None, permission_key: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """Sets HTTP headers on the file. @@ -1206,33 +1261,39 @@ def set_http_headers( :returns: File-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) - file_content_length = kwargs.pop('size', None) - file_http_headers = FileHTTPHeaders( - file_cache_control=content_settings.cache_control, - file_content_type=content_settings.content_type, - file_content_md5=bytearray(content_settings.content_md5) if content_settings.content_md5 else None, - file_content_encoding=content_settings.content_encoding, - file_content_language=content_settings.content_language, - file_content_disposition=content_settings.content_disposition - ) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) + file_content_length = kwargs.pop("size", None) + file_http_headers = { + "file_cache_control": content_settings.cache_control, + "file_content_type": content_settings.content_type, + "file_content_md5": bytearray(content_settings.content_md5) if content_settings.content_md5 else None, + "file_content_encoding": content_settings.content_encoding, + "file_content_language": content_settings.content_language, + "file_content_disposition": content_settings.content_disposition, + } file_permission = _get_file_permission(file_permission, permission_key, None) - file_change_time = kwargs.pop('file_change_time', None) + file_change_time = kwargs.pop("file_change_time", None) try: - return cast(Dict[str, Any], self._client.file.set_http_headers( - file_content_length=file_content_length, - file_http_headers=file_http_headers, - file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - file_permission=file_permission, - file_permission_key=permission_key, - lease_access_conditions=access_conditions, - timeout=timeout, - cls=return_response_headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.file.set_http_headers( + file_content_length=file_content_length, + **file_http_headers, + file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, + file_creation_time=_datetime_to_str(file_creation_time), + file_last_write_time=_datetime_to_str(file_last_write_time), + file_change_time=_datetime_to_str(file_change_time), + file_permission=file_permission, + file_permission_key=permission_key, + lease_id=access_conditions, + timeout=timeout, + cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1264,28 +1325,29 @@ def set_file_metadata(self, metadata: Optional[Dict[str, Any]] = None, **kwargs: :returns: File-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], self._client.file.set_metadata( - timeout=timeout, - cls=return_response_headers, - headers=headers, - metadata=metadata, - lease_access_conditions=access_conditions, - **kwargs)) + return cast( + Dict[str, Any], + self._client.file.set_metadata( + timeout=timeout, + cls=return_response_headers, + headers=headers, + metadata=metadata, + lease_id=access_conditions, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace - def upload_range( - self, data: bytes, - offset: int, - length: int, - **kwargs: Any - ) -> Dict[str, Any]: + def upload_range(self, data: bytes, offset: int, length: int, **kwargs: Any) -> Dict[str, Any]: """Upload a range of bytes to a file. :param bytes data: @@ -1331,37 +1393,40 @@ def upload_range( :returns: File-updated property dict (Etag and last modified). :rtype: Dict[str, Any] """ - validate_content = kwargs.pop('validate_content', False) - timeout = kwargs.pop('timeout', None) - encoding = kwargs.pop('encoding', 'UTF-8') - file_last_write_mode = kwargs.pop('file_last_write_mode', None) + validate_content = kwargs.pop("validate_content", False) + timeout = kwargs.pop("timeout", None) + encoding = kwargs.pop("encoding", "UTF-8") + file_last_write_mode = kwargs.pop("file_last_write_mode", None) if isinstance(data, str): data = data.encode(encoding) end_range = offset + length - 1 # Reformat to an inclusive range index - content_range = f'bytes={offset}-{end_range}' - access_conditions = get_access_conditions(kwargs.pop('lease', None)) + content_range = f"bytes={offset}-{end_range}" + access_conditions = get_access_conditions(kwargs.pop("lease", None)) try: - return cast(Dict[str, Any], self._client.file.upload_range( - range=content_range, - content_length=length, - optionalbody=data, - timeout=timeout, - validate_content=validate_content, - file_last_written_mode=file_last_write_mode, - lease_access_conditions=access_conditions, - cls=return_response_headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.file.upload_range( + range=content_range, + file_range_write="update", + content_length=length, + optional_body=data, + timeout=timeout, + validate_content=validate_content, + file_last_written_mode=file_last_write_mode, + lease_id=access_conditions, + cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace def upload_range_from_url( - self, source_url: str, - offset: int, - length: int, - source_offset: int, - **kwargs: Any + self, source_url: str, offset: int, length: int, source_offset: int, **kwargs: Any ) -> Dict[str, Any]: """ Writes the bytes from one Azure File endpoint into the specified range of another Azure File endpoint. @@ -1431,12 +1496,11 @@ def upload_range_from_url( :rtype: dict[str, Any] """ options = _upload_range_from_url_options( - source_url=source_url, - offset=offset, - length=length, - source_offset=source_offset, - **kwargs + source_url=source_url, offset=offset, length=length, source_offset=source_offset, **kwargs ) + options["allow_trailing_dot"] = self.allow_trailing_dot + options["allow_source_trailing_dot"] = self.allow_source_trailing_dot + options["file_request_intent"] = self.file_request_intent try: return cast(Dict[str, Any], self._client.file.upload_range_from_url(**options)) except HttpResponseError as error: @@ -1444,9 +1508,7 @@ def upload_range_from_url( @distributed_trace def get_ranges( - self, offset: Optional[int] = None, - length: Optional[int] = None, - **kwargs: Any + self, offset: Optional[int] = None, length: Optional[int] = None, **kwargs: Any ) -> List[Dict[str, int]]: """Returns the list of valid page ranges for a file or snapshot of a file. @@ -1472,25 +1534,24 @@ def get_ranges( A list of valid ranges. :rtype: List[dict[str, int]] """ - options = _get_ranges_options( - snapshot=self.snapshot, - offset=offset, - length=length, - **kwargs) + options = _get_ranges_options(snapshot=self.snapshot, offset=offset, length=length, **kwargs) + options["allow_trailing_dot"] = self.allow_trailing_dot + options["file_request_intent"] = self.file_request_intent try: ranges = self._client.file.get_range_list(**options) except HttpResponseError as error: process_storage_error(error) - return [{'start': file_range.start, 'end': file_range.end} for file_range in ranges.ranges] + return [{"start": file_range.start, "end": file_range.end} for file_range in (ranges.ranges or [])] @distributed_trace def get_ranges_diff( - self, previous_sharesnapshot: Union[str, Dict[str, Any]], + self, + previous_sharesnapshot: Union[str, Dict[str, Any]], offset: Optional[int] = None, length: Optional[int] = None, *, include_renames: Optional[bool] = None, - **kwargs: Any + **kwargs: Any, ) -> Tuple[List[Dict[str, int]], List[Dict[str, int]]]: """Returns the list of valid page ranges for a file or snapshot of a file. @@ -1531,7 +1592,10 @@ def get_ranges_diff( length=length, previous_sharesnapshot=previous_sharesnapshot, support_rename=include_renames, - **kwargs) + **kwargs, + ) + options["allow_trailing_dot"] = self.allow_trailing_dot + options["file_request_intent"] = self.file_request_intent try: ranges = self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1565,25 +1629,31 @@ def clear_range(self, offset: int, length: int, **kwargs: Any) -> Dict[str, Any] :returns: File-updated property dict (Etag and last modified). :rtype: Dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) if offset is None or offset % 512 != 0: raise ValueError("offset must be an integer that aligns with 512 bytes file size") if length is None or length % 512 != 0: raise ValueError("length must be an integer that aligns with 512 bytes file size") end_range = length + offset - 1 # Reformat to an inclusive range index - content_range = f'bytes={offset}-{end_range}' + content_range = f"bytes={offset}-{end_range}" try: - return cast(Dict[str, Any], self._client.file.upload_range( - timeout=timeout, - cls=return_response_headers, - content_length=0, - optionalbody=None, - file_range_write="clear", - range=content_range, - lease_access_conditions=access_conditions, - **kwargs)) + return cast( + Dict[str, Any], + self._client.file.upload_range( + timeout=timeout, + cls=return_response_headers, + content_length=0, + optional_body=None, + file_range_write="clear", + range=content_range, + lease_id=access_conditions, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1609,19 +1679,25 @@ def resize_file(self, size: int, **kwargs: Any) -> Dict[str, Any]: :returns: File-updated property dict (Etag and last modified). :rtype: Dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - return cast(Dict[str, Any], self._client.file.set_http_headers( - file_content_length=size, - file_attributes=None, - file_creation_time=None, - file_last_write_time=None, - file_permission="preserve", - lease_access_conditions=access_conditions, - cls=return_response_headers, - timeout=timeout, - **kwargs)) + return cast( + Dict[str, Any], + self._client.file.set_http_headers( + file_content_length=size, + file_attributes=None, + file_creation_time=None, + file_last_write_time=None, + file_permission="preserve", + lease_id=access_conditions, + cls=return_response_headers, + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1638,16 +1714,17 @@ def list_handles(self, **kwargs: Any) -> ItemPaged[Handle]: :returns: An auto-paging iterable of Handle :rtype: ~azure.core.paging.ItemPaged[~azure.storage.fileshare.Handle] """ - timeout = kwargs.pop('timeout', None) - results_per_page = kwargs.pop('results_per_page', None) + timeout = kwargs.pop("timeout", None) + results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( self._client.file.list_handles, sharesnapshot=self.snapshot, timeout=timeout, - **kwargs) - return ItemPaged( - command, results_per_page=results_per_page, - page_iterator_class=HandlesPaged) + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) + return ItemPaged(command, results_per_page=results_per_page, page_iterator_class=HandlesPaged) @distributed_trace def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[str, int]: @@ -1671,19 +1748,21 @@ def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[str, i handle_id = handle.id else: handle_id = handle - if handle_id == '*': + if handle_id == "*": raise ValueError("Handle ID '*' is not supported. Use 'close_all_handles' instead.") try: response = self._client.file.force_close_handles( - handle_id, + handle_id=handle_id, marker=None, sharesnapshot=self.snapshot, cls=return_response_headers, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) return { - 'closed_handles_count': response.get('number_of_handles_closed', 0), - 'failed_handles_count': response.get('number_of_handles_failed', 0) + "closed_handles_count": response.get("number_of_handles_closed", 0), + "failed_handles_count": response.get("number_of_handles_failed", 0), } except HttpResponseError as error: process_storage_error(error) @@ -1704,7 +1783,7 @@ def close_all_handles(self, **kwargs: Any) -> Dict[str, int]: and the number of handles failed to close in a dict. :rtype: dict[str, int] """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) start_time = time.time() try_close = True @@ -1714,33 +1793,33 @@ def close_all_handles(self, **kwargs: Any) -> Dict[str, int]: while try_close: try: response = self._client.file.force_close_handles( - handle_id='*', + handle_id="*", timeout=timeout, marker=continuation_token, sharesnapshot=self.snapshot, cls=return_response_headers, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) except HttpResponseError as error: process_storage_error(error) - continuation_token = response.get('marker') + continuation_token = response.get("marker") try_close = bool(continuation_token) - total_closed += response.get('number_of_handles_closed', 0) - total_failed += response.get('number_of_handles_failed', 0) + total_closed += response.get("number_of_handles_closed", 0) + total_failed += response.get("number_of_handles_failed", 0) if timeout: timeout = max(0, timeout - (time.time() - start_time)) - return { - 'closed_handles_count': total_closed, - 'failed_handles_count': total_failed - } + return {"closed_handles_count": total_closed, "failed_handles_count": total_failed} @distributed_trace def create_hardlink( - self, target: str, + self, + target: str, *, lease: Optional[Union[ShareLeaseClient, str]] = None, timeout: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """NFS only. Creates a hard link to the file specified by path. @@ -1762,19 +1841,24 @@ def create_hardlink( :rtype: dict[str, Any] """ try: - return cast(Dict[str, Any], self._client.file.create_hard_link( - target_file=target, - lease_access_conditions=lease, - timeout=timeout, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + self._client.file.create_hard_link( + target_file=target, + lease_id=lease, + timeout=timeout, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace def create_symlink( - self, target: str, + self, + target: str, *, metadata: Optional[Dict[str, str]] = None, file_creation_time: Optional[Union[str, datetime]] = None, @@ -1783,7 +1867,7 @@ def create_symlink( group: Optional[str] = None, lease: Optional[Union[ShareLeaseClient, str]] = None, timeout: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """NFS only. Creates a symbolic link to the specified file. @@ -1811,28 +1895,27 @@ def create_symlink( :rtype: dict[str, Any] """ try: - return cast(Dict[str, Any], self._client.file.create_symbolic_link( - link_text=target, - metadata=metadata, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - owner=owner, - group=group, - lease_access_conditions=lease, - timeout=timeout, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + self._client.file.create_symbolic_link( + link_text=target, + metadata=metadata, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + owner=owner, + group=group, + lease_id=lease, + timeout=timeout, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace - def get_symlink( - self, - *, - timeout: Optional[int] = None, - **kwargs: Any - ) -> Dict[str, Any]: + def get_symlink(self, *, timeout: Optional[int] = None, **kwargs: Any) -> Dict[str, Any]: """NFS only. Gets the symbolic link for the file client. :keyword int timeout: @@ -1845,10 +1928,14 @@ def get_symlink( :rtype: dict[str, Any] """ try: - return cast(Dict[str, Any], self._client.file.get_symbolic_link( - timeout=timeout, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + self._client.file.get_symbolic_link( + timeout=timeout, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client_helpers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client_helpers.py index ea225f3c596c..e0bfe66d4769 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client_helpers.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client_helpers.py @@ -4,10 +4,7 @@ # license information. # -------------------------------------------------------------------------- -from typing import ( - Any, Dict, List, Optional, Tuple, Union, - TYPE_CHECKING -) +from typing import Any, Dict, List, Optional, Tuple, Union, TYPE_CHECKING from urllib.parse import quote, unquote, urlparse from ._serialize import get_access_conditions, get_source_conditions @@ -20,11 +17,11 @@ def _parse_url(account_url: str, share_name: str, file_path: str) -> "ParseResult": try: - if not account_url.lower().startswith('http'): + if not account_url.lower().startswith("http"): account_url = "https://" + account_url except AttributeError as exc: raise ValueError("Account URL must be a string.") from exc - parsed_url = urlparse(account_url.rstrip('/')) + parsed_url = urlparse(account_url.rstrip("/")) if not (share_name and file_path): raise ValueError("Please specify a share name and file name.") if not parsed_url.netloc: @@ -33,48 +30,38 @@ def _parse_url(account_url: str, share_name: str, file_path: str) -> "ParseResul def _from_file_url( - file_url: str, - snapshot: Optional[Union[str, Dict[str, Any]]] = None + file_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None ) -> Tuple[str, str, str, Optional[Union[str, Dict[str, Any]]]]: try: - if not file_url.lower().startswith('http'): + if not file_url.lower().startswith("http"): file_url = "https://" + file_url except AttributeError as exc: raise ValueError("File URL must be a string.") from exc - parsed_url = urlparse(file_url.rstrip('/')) + parsed_url = urlparse(file_url.rstrip("/")) if not (parsed_url.netloc and parsed_url.path): raise ValueError(f"Invalid URL: {file_url}") - account_url = parsed_url.netloc.rstrip('/') + "?" + parsed_url.query + account_url = parsed_url.netloc.rstrip("/") + "?" + parsed_url.query - path_share, _, path_file = parsed_url.path.lstrip('/').partition('/') + path_share, _, path_file = parsed_url.path.lstrip("/").partition("/") path_snapshot, _ = parse_query(parsed_url.query) snapshot = snapshot or path_snapshot share_name = unquote(path_share) - file_path = '/'.join([unquote(p) for p in path_file.split('/')]) + file_path = "/".join([unquote(p) for p in path_file.split("/")]) return account_url, share_name, file_path, snapshot -def _format_url( - scheme: str, - hostname: str, - share_name: Union[str, bytes], - file_path: List[str], - query_str: str -) -> str: +def _format_url(scheme: str, hostname: str, share_name: Union[str, bytes], file_path: List[str], query_str: str) -> str: if isinstance(share_name, str): - share_name = share_name.encode('UTF-8') - return (f"{scheme}://{hostname}/{quote(share_name)}" - f"/{'/'.join([quote(p, safe='~') for p in file_path])}{query_str}") + share_name = share_name.encode("UTF-8") + return ( + f"{scheme}://{hostname}/{quote(share_name)}" f"/{'/'.join([quote(p, safe='~') for p in file_path])}{query_str}" + ) def _upload_range_from_url_options( - source_url: str, - offset: int, - length: int, - source_offset: int, - **kwargs: Any + source_url: str, offset: int, length: int, source_offset: int, **kwargs: Any ) -> Dict[str, Any]: if offset is None: raise ValueError("offset must be provided.") @@ -85,24 +72,27 @@ def _upload_range_from_url_options( # Format range end_range = offset + length - 1 - destination_range = f'bytes={offset}-{end_range}' - source_range = f'bytes={source_offset}-{source_offset + length - 1}' - source_authorization = kwargs.pop('source_authorization', None) - source_mod_conditions = get_source_conditions(kwargs) - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - file_last_write_mode = kwargs.pop('file_last_write_mode', None) + destination_range = f"bytes={offset}-{end_range}" + source_range = f"bytes={source_offset}-{source_offset + length - 1}" + source_authorization = kwargs.pop("source_authorization", None) + _source_mod_conditions = get_source_conditions(kwargs) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + file_last_write_mode = kwargs.pop("file_last_write_mode", None) options = { - 'copy_source_authorization': source_authorization, - 'copy_source': source_url, - 'content_length': 0, - 'source_range': source_range, - 'range': destination_range, - 'file_last_written_mode': file_last_write_mode, - 'source_modified_access_conditions': source_mod_conditions, - 'lease_access_conditions': access_conditions, - 'timeout': kwargs.pop('timeout', None), - 'cls': return_response_headers + "copy_source_authorization": source_authorization, + "copy_source": source_url, + "content_length": 0, + "source_range": source_range, + "range": destination_range, + "file_range_write_from_url": "update", + "file_last_written_mode": file_last_write_mode, + "source_content_crc64": kwargs.pop("source_content_crc64", None), + "source_if_match_crc64": kwargs.pop("source_if_match_crc64", None), + "source_if_none_match_crc64": kwargs.pop("source_if_none_match_crc64", None), + "lease_id": access_conditions, + "timeout": kwargs.pop("timeout", None), + "cls": return_response_headers, } options.update(kwargs) @@ -114,32 +104,32 @@ def _get_ranges_options( offset: Optional[int] = None, length: Optional[int] = None, previous_sharesnapshot: Optional[Union[str, Dict[str, Any]]] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: - access_conditions = get_access_conditions(kwargs.pop('lease', None)) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) content_range = None if offset: if length: end_range = offset + length - 1 # Reformat to an inclusive range index - content_range = f'bytes={offset}-{end_range}' + content_range = f"bytes={offset}-{end_range}" else: - content_range = f'bytes={offset}-' + content_range = f"bytes={offset}-" options = { - 'sharesnapshot': snapshot, - 'lease_access_conditions': access_conditions, - 'timeout': kwargs.pop('timeout', None), - 'range': content_range + "sharesnapshot": snapshot, + "lease_id": access_conditions, + "timeout": kwargs.pop("timeout", None), + "range": content_range, } if previous_sharesnapshot: - if hasattr(previous_sharesnapshot, 'snapshot'): - options['prevsharesnapshot'] = previous_sharesnapshot.snapshot + if hasattr(previous_sharesnapshot, "snapshot"): + options["prevsharesnapshot"] = previous_sharesnapshot.snapshot elif isinstance(previous_sharesnapshot, Dict): - options['prevsharesnapshot'] = previous_sharesnapshot['snapshot'] + options["prevsharesnapshot"] = previous_sharesnapshot["snapshot"] else: - options['prevsharesnapshot'] = previous_sharesnapshot + options["prevsharesnapshot"] = previous_sharesnapshot options.update(kwargs) return options diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/__init__.py index b4f1dd31c73a..95af3b88f994 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,7 +12,10 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._azure_file_storage import AzureFileStorage # type: ignore +from ._client import FileClient # type: ignore +from ._version import VERSION + +__version__ = VERSION try: from ._patch import __all__ as _patch_all @@ -22,7 +25,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureFileStorage", + "FileClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_azure_file_storage.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py similarity index 61% rename from sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_azure_file_storage.py rename to sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py index cea1a9e2ac4c..6540b3fde6f6 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_azure_file_storage.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py @@ -2,74 +2,51 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Optional, Union +from typing import Any, TYPE_CHECKING from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from . import models as _models -from ._configuration import AzureFileStorageConfiguration +from ._configuration import FileClientConfiguration from ._utils.serialization import Deserializer, Serializer from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class AzureFileStorage: # pylint: disable=client-accepts-api-version-keyword - """AzureFileStorage. - :ivar service: ServiceOperations operations - :vartype service: azure.storage.fileshare.operations.ServiceOperations - :ivar share: ShareOperations operations - :vartype share: azure.storage.fileshare.operations.ShareOperations +class FileClient: # pylint: disable=client-accepts-api-version-keyword + """Azure File Storage provides scalable file shares in the cloud using SMB and NFS protocols. + :ivar directory: DirectoryOperations operations :vartype directory: azure.storage.fileshare.operations.DirectoryOperations :ivar file: FileOperations operations :vartype file: azure.storage.fileshare.operations.FileOperations - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str + :ivar service: ServiceOperations operations + :vartype service: azure.storage.fileshare.operations.ServiceOperations + :ivar share: ShareOperations operations + :vartype share: azure.storage.fileshare.operations.ShareOperations :param url: The URL of the service account, share, directory or file that is the target of the desired operation. Required. :type url: str - :param base_url: Service URL. Required. Default value is "". - :type base_url: str - :param file_request_intent: Valid value is backup. "backup" Default value is None. - :type file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent - :param allow_trailing_dot: If true, the trailing dot will not be trimmed from the target URI. - Default value is None. - :type allow_trailing_dot: bool - :param allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the source - URI. Default value is None. - :type allow_source_trailing_dot: bool - :keyword file_range_write_from_url: Only update is supported: - Update: Writes the bytes - downloaded from the source url into the specified range. Default value is "update". Note that - overriding this default value may result in unsupported behavior. - :paramtype file_range_write_from_url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-06-06". Default value is "2026-06-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, - version: str, - url: str, - base_url: str = "", - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - allow_trailing_dot: Optional[bool] = None, - allow_source_trailing_dot: Optional[bool] = None, - **kwargs: Any - ) -> None: - self._config = AzureFileStorageConfiguration( - version=version, - url=url, - file_request_intent=file_request_intent, - allow_trailing_dot=allow_trailing_dot, - allow_source_trailing_dot=allow_source_trailing_dot, - **kwargs - ) + def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{url}" + self._config = FileClientConfiguration(url=url, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -88,24 +65,23 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: PipelineClient = PipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) - self.share = ShareOperations(self._client, self._config, self._serialize, self._deserialize) self.directory = DirectoryOperations(self._client, self._config, self._serialize, self._deserialize) self.file = FileOperations(self._client, self._config, self._serialize, self._deserialize) + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.share = ShareOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = client._send_request(request) + >>> response = client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -118,7 +94,11 @@ def _send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_configuration.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_configuration.py index 51f09f3c22f7..a2935329dbae 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_configuration.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_configuration.py @@ -2,67 +2,50 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Literal, Optional, Union +from typing import Any, TYPE_CHECKING from azure.core.pipeline import policies -from . import models as _models +from ._version import VERSION -VERSION = "unknown" +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class AzureFileStorageConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for AzureFileStorage. +class FileClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for FileClient. Note that all parameters used to create this instance are saved as instance attributes. - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str :param url: The URL of the service account, share, directory or file that is the target of the desired operation. Required. :type url: str - :param file_request_intent: Valid value is backup. "backup" Default value is None. - :type file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent - :param allow_trailing_dot: If true, the trailing dot will not be trimmed from the target URI. - Default value is None. - :type allow_trailing_dot: bool - :param allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the source - URI. Default value is None. - :type allow_source_trailing_dot: bool - :keyword file_range_write_from_url: Only update is supported: - Update: Writes the bytes - downloaded from the source url into the specified range. Default value is "update". Note that - overriding this default value may result in unsupported behavior. - :paramtype file_range_write_from_url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-06-06". Default value is "2026-06-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str """ - def __init__( - self, - version: str, - url: str, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - allow_trailing_dot: Optional[bool] = None, - allow_source_trailing_dot: Optional[bool] = None, - **kwargs: Any - ) -> None: - file_range_write_from_url: Literal["update"] = kwargs.pop("file_range_write_from_url", "update") + def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> None: + version: str = kwargs.pop("version", "2026-06-06") - if version is None: - raise ValueError("Parameter 'version' must not be None.") if url is None: raise ValueError("Parameter 'url' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") - self.version = version self.url = url - self.file_request_intent = file_request_intent - self.allow_trailing_dot = allow_trailing_dot - self.allow_source_trailing_dot = allow_source_trailing_dot - self.file_range_write_from_url = file_range_write_from_url - kwargs.setdefault("sdk_moniker", "azurefilestorage/{}".format(VERSION)) + self.credential = credential + self.version = version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://storage.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "storage-file-share/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) @@ -76,3 +59,7 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_patch.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_patch.py index f7dd32510333..2cf4b1394be1 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_patch.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_patch.py @@ -1,14 +1,134 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +from typing import Any, Optional, TYPE_CHECKING -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +from azure.core import PipelineClient +from azure.core.pipeline import Pipeline, PipelineRequest +from azure.core.pipeline.policies import SansIOHTTPPolicy + +from ._client import FileClient as GeneratedFileClient +from ._configuration import FileClientConfiguration as GeneratedFileClientConfiguration + +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + + +class RangeHeaderPolicy(SansIOHTTPPolicy): + """Policy that converts the 'Range' header to 'x-ms-range'.""" + + def on_request(self, request: PipelineRequest) -> None: + range_value = request.http_request.headers.pop("Range", None) + if range_value is not None: + request.http_request.headers["x-ms-range"] = range_value + + +class FileClientConfiguration(GeneratedFileClientConfiguration): + """Configuration for FileClient that allows optional credentials. + + This class overrides the generated configuration to allow None credentials + for anonymous access or when a pre-built pipeline handles auth. + + :param url: The URL of the service account, share, directory or file that is the target of the + desired operation. Required. + :type url: str + :param credential: Credential used to authenticate requests to the service. Can be None. + :type credential: ~azure.core.credentials.TokenCredential or None + :keyword version: Specifies the version of the operation to use for this request. + :paramtype version: str + """ + + def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **kwargs: Any) -> None: + if url is None: + raise ValueError("Parameter 'url' must not be None.") + + version: str = kwargs.pop("version", "2026-06-06") + self.url = url + self.credential = credential + self.version = version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://storage.azure.com/.default"]) + from ._version import VERSION + + kwargs.setdefault("sdk_moniker", "storage-file-share/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + +class AzureFileStorage(GeneratedFileClient): + """Subclass of the generated FileClient that allows optional credentials, + accepts a pre-built pipeline, and injects the RangeHeaderPolicy. + + :param url: The URL of the service account, share, directory or file. + :type url: str + :param credential: Credential used to authenticate requests to the service. + Can be None when a pre-built pipeline is provided. + :type credential: ~azure.core.credentials.TokenCredential or None + :keyword pipeline: A pre-built pipeline to use instead of constructing one. + :paramtype pipeline: ~azure.core.pipeline.Pipeline + :keyword version: Specifies the version of the operation to use for this request. + :paramtype version: str + """ + + def __init__( + self, url: str, credential: Optional["TokenCredential"] = None, *, pipeline: Any = None, **kwargs: Any + ) -> None: + from azure.core.pipeline import policies + + from ._utils.serialization import Deserializer, Serializer + from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations + + _endpoint = "{url}" + self._config = FileClientConfiguration(url=url, credential=credential, **kwargs) + + if pipeline is not None: + # Wrap the pre-built pipeline to inject RangeHeaderPolicy + _wrapped_pipeline = Pipeline( + transport=pipeline._transport, + policies=[RangeHeaderPolicy()] + list(pipeline._impl_policies), + ) + self._client = PipelineClient(base_url=_endpoint, pipeline=_wrapped_pipeline) + else: + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + RangeHeaderPolicy(), + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.share = ShareOperations(self._client, self._config, self._serialize, self._deserialize) + self.directory = DirectoryOperations(self._client, self._config, self._serialize, self._deserialize) + self.file = FileOperations(self._client, self._config, self._serialize, self._deserialize) + + +# Alias so that `from ._patch import *` overrides the generated FileClient +FileClient = AzureFileStorage + + +__all__: list[str] = ["FileClient"] def patch_sdk(): diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/__init__.py index 0af9b28f6607..8026245c2abc 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/__init__.py @@ -1,6 +1,6 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/model_base.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/model_base.py new file mode 100644 index 000000000000..eef4e52ed1a0 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/model_base.py @@ -0,0 +1,1459 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=protected-access, broad-except + +import copy +import calendar +import decimal +import functools +import sys +import logging +import base64 +import re +import typing +import enum +import email.utils +from datetime import datetime, date, time, timedelta, timezone +from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping +from typing_extensions import Self +import isodate +from azure.core.exceptions import DeserializationError +from azure.core import CaseInsensitiveEnumMeta +from azure.core.pipeline import PipelineResponse +from azure.core.serialization import _Null +from azure.core.rest import HttpResponse + +_LOGGER = logging.getLogger(__name__) + +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] + +TZ_UTC = timezone.utc +_T = typing.TypeVar("_T") +_NONE_TYPE = type(None) + + +def _timedelta_as_isostr(td: timedelta) -> str: + """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' + + Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython + + :param timedelta td: The timedelta to convert + :rtype: str + :return: ISO8601 version of this timedelta + """ + + # Split seconds to larger units + seconds = td.total_seconds() + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + days, hours = divmod(hours, 24) + + days, hours, minutes = list(map(int, (days, hours, minutes))) + seconds = round(seconds, 6) + + # Build date + date_str = "" + if days: + date_str = "%sD" % days + + if hours or minutes or seconds: + # Build time + time_str = "T" + + # Hours + bigger_exists = date_str or hours + if bigger_exists: + time_str += "{:02}H".format(hours) + + # Minutes + bigger_exists = bigger_exists or minutes + if bigger_exists: + time_str += "{:02}M".format(minutes) + + # Seconds + try: + if seconds.is_integer(): + seconds_string = "{:02}".format(int(seconds)) + else: + # 9 chars long w/ leading 0, 6 digits after decimal + seconds_string = "%09.6f" % seconds + # Remove trailing zeros + seconds_string = seconds_string.rstrip("0") + except AttributeError: # int.is_integer() raises + seconds_string = "{:02}".format(seconds) + + time_str += "{}S".format(seconds_string) + else: + time_str = "" + + return "P" + date_str + time_str + + +def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: + encoded = base64.b64encode(o).decode() + if format == "base64url": + return encoded.strip("=").replace("+", "-").replace("/", "_") + return encoded + + +def _serialize_datetime(o, format: typing.Optional[str] = None): + if hasattr(o, "year") and hasattr(o, "hour"): + if format == "rfc7231": + return email.utils.format_datetime(o, usegmt=True) + if format == "unix-timestamp": + return int(calendar.timegm(o.utctimetuple())) + + # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) + if not o.tzinfo: + iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() + else: + iso_formatted = o.astimezone(TZ_UTC).isoformat() + # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) + return iso_formatted.replace("+00:00", "Z") + # Next try datetime.date or datetime.time + return o.isoformat() + + +def _is_readonly(p): + try: + return p._visibility == ["read"] + except AttributeError: + return False + + +class SdkJSONEncoder(JSONEncoder): + """A JSON encoder that's capable of serializing datetime objects and bytes.""" + + def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): + super().__init__(*args, **kwargs) + self.exclude_readonly = exclude_readonly + self.format = format + + def default(self, o): # pylint: disable=too-many-return-statements + if _is_model(o): + if self.exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + return {k: v for k, v in o.items() if k not in readonly_props} + return dict(o.items()) + try: + return super(SdkJSONEncoder, self).default(o) + except TypeError: + if isinstance(o, _Null): + return None + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, self.format) + try: + # First try datetime.datetime + return _serialize_datetime(o, self.format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return super(SdkJSONEncoder, self).default(o) + + +_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") +_VALID_RFC7231 = re.compile( + r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" + r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" +) + +_ARRAY_ENCODE_MAPPING = { + "pipeDelimited": "|", + "spaceDelimited": " ", + "commaDelimited": ",", + "newlineDelimited": "\n", +} + + +def _deserialize_array_encoded(delimit: str, attr): + if isinstance(attr, str): + if attr == "": + return [] + return attr.split(delimit) + return attr + + +def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + attr = attr.upper() + match = _VALID_DATE.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + return date_obj # type: ignore[no-any-return] + + +def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: + """Deserialize RFC7231 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + match = _VALID_RFC7231.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + return email.utils.parsedate_to_datetime(attr) + + +def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: + """Deserialize unix timestamp into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: ~datetime.datetime + :returns: The datetime object from that input + """ + if isinstance(attr, datetime): + # i'm already deserialized + return attr + return datetime.fromtimestamp(attr, TZ_UTC) + + +def _deserialize_date(attr: typing.Union[str, date]) -> date: + """Deserialize ISO-8601 formatted string into Date object. + :param str attr: response string to be deserialized. + :rtype: date + :returns: The date object from that input + """ + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + if isinstance(attr, date): + return attr + return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore + + +def _deserialize_time(attr: typing.Union[str, time]) -> time: + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :returns: The time object from that input + """ + if isinstance(attr, time): + return attr + return isodate.parse_time(attr) # type: ignore[no-any-return] + + +def _deserialize_bytes(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + return bytes(base64.b64decode(attr)) + + +def _deserialize_bytes_base64(attr): + if isinstance(attr, (bytes, bytearray)): + return attr + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return bytes(base64.b64decode(encoded)) + + +def _deserialize_duration(attr): + if isinstance(attr, timedelta): + return attr + return isodate.parse_duration(attr) + + +def _deserialize_decimal(attr): + if isinstance(attr, decimal.Decimal): + return attr + return decimal.Decimal(str(attr)) + + +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + +_DESERIALIZE_MAPPING = { + datetime: _deserialize_datetime, + date: _deserialize_date, + time: _deserialize_time, + bytes: _deserialize_bytes, + bytearray: _deserialize_bytes, + timedelta: _deserialize_duration, + typing.Any: lambda x: x, + decimal.Decimal: _deserialize_decimal, +} + +_DESERIALIZE_MAPPING_WITHFORMAT = { + "rfc3339": _deserialize_datetime, + "rfc7231": _deserialize_datetime_rfc7231, + "unix-timestamp": _deserialize_datetime_unix_timestamp, + "base64": _deserialize_bytes, + "base64url": _deserialize_bytes_base64, +} + + +def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str + if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: + return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) + if rf and rf._format: + return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore + + +def _get_type_alias_type(module_name: str, alias_name: str): + types = { + k: v + for k, v in sys.modules[module_name].__dict__.items() + if isinstance(v, typing._GenericAlias) # type: ignore + } + if alias_name not in types: + return alias_name + return types[alias_name] + + +def _get_model(module_name: str, model_name: str): + models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} + module_end = module_name.rsplit(".", 1)[0] + models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) + if isinstance(model_name, str): + model_name = model_name.split(".")[-1] + if model_name not in models: + return model_name + return models[model_name] + + +_UNSET = object() + + +class _MyMutableMapping(MutableMapping[str, typing.Any]): + def __init__(self, data: dict[str, typing.Any]) -> None: + self._data = data + + def __contains__(self, key: typing.Any) -> bool: + return key in self._data + + def __getitem__(self, key: str) -> typing.Any: + # If this key has been deserialized (for mutable types), we need to handle serialization + if hasattr(self, "_attr_to_rest_field"): + cache_attr = f"_deserialized_{key}" + if hasattr(self, cache_attr): + rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) + if rf: + value = self._data.get(key) + if isinstance(value, (dict, list, set)): + # For mutable types, serialize and return + # But also update _data with serialized form and clear flag + # so mutations via this returned value affect _data + serialized = _serialize(value, rf._format) + # If serialized form is same type (no transformation needed), + # return _data directly so mutations work + if isinstance(serialized, type(value)) and serialized == value: + return self._data.get(key) + # Otherwise return serialized copy and clear flag + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + # Store serialized form back + self._data[key] = serialized + return serialized + return self._data.__getitem__(key) + + def __setitem__(self, key: str, value: typing.Any) -> None: + # Clear any cached deserialized value when setting through dictionary access + cache_attr = f"_deserialized_{key}" + try: + object.__delattr__(self, cache_attr) + except AttributeError: + pass + self._data.__setitem__(key, value) + + def __delitem__(self, key: str) -> None: + self._data.__delitem__(key) + + def __iter__(self) -> typing.Iterator[typing.Any]: + return self._data.__iter__() + + def __len__(self) -> int: + return self._data.__len__() + + def __ne__(self, other: typing.Any) -> bool: + return not self.__eq__(other) + + def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ + return self._data.keys() + + def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ + return self._data.values() + + def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ + return self._data.items() + + def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ + try: + return self[key] + except KeyError: + return default + + @typing.overload + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ + if default is _UNSET: + return self._data.pop(key) + return self._data.pop(key, default) + + def popitem(self) -> tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ + return self._data.popitem() + + def clear(self) -> None: + """ + Remove all items from D. + """ + self._data.clear() + + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ + self._data.update(*args, **kwargs) + + @typing.overload + def setdefault(self, key: str, default: None = None) -> None: ... + + @typing.overload + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ + if default is _UNSET: + return self._data.setdefault(key) + return self._data.setdefault(key, default) + + def __eq__(self, other: typing.Any) -> bool: + if isinstance(other, _MyMutableMapping): + return self._data == other._data + try: + other_model = self.__class__(other) + except Exception: + return False + return self._data == other_model._data + + def __repr__(self) -> str: + return str(self._data) + + +def _is_model(obj: typing.Any) -> bool: + return getattr(obj, "_is_model", False) + + +def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements + if isinstance(o, list): + if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): + return _ARRAY_ENCODE_MAPPING[format].join(o) + return [_serialize(x, format) for x in o] + if isinstance(o, dict): + return {k: _serialize(v, format) for k, v in o.items()} + if isinstance(o, set): + return {_serialize(x, format) for x in o} + if isinstance(o, tuple): + return tuple(_serialize(x, format) for x in o) + if isinstance(o, (bytes, bytearray)): + return _serialize_bytes(o, format) + if isinstance(o, decimal.Decimal): + return float(o) + if isinstance(o, enum.Enum): + return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o + try: + # First try datetime.datetime + return _serialize_datetime(o, format) + except AttributeError: + pass + # Last, try datetime.timedelta + try: + return _timedelta_as_isostr(o) + except AttributeError: + # This will be raised when it hits value.total_seconds in the method above + pass + return o + + +def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: + try: + return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) + except StopIteration: + return None + + +def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: + if not rf: + return _serialize(value, None) + if rf._is_multipart_file_input: + return value + if rf._is_model: + return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) + return _serialize(value, rf._format) + + +class Model(_MyMutableMapping): + _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: set[str] = set() + + def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: + class_name = self.__class__.__name__ + if len(args) > 1: + raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") + dict_to_pass = { + rest_field._rest_name: rest_field._default + for rest_field in self._attr_to_rest_field.values() + if rest_field._default is not _UNSET + } + if args: + if isinstance(args[0], ET.Element): + dict_to_pass.update(self._init_from_xml(args[0])) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) + else: + non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] + if non_attr_kwargs: + # actual type errors only throw the first wrong keyword arg they see, so following that. + raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") + dict_to_pass.update( + { + self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) + for k, v in kwargs.items() + if v is not None + } + ) + super().__init__(dict_to_pass) + + def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: + """Deserialize an XML element into a dict mapping rest field names to values. + + :param ET.Element element: The XML element to deserialize from. + :returns: A dictionary of rest_name to deserialized value pairs. + :rtype: dict + """ + result: dict[str, typing.Any] = {} + model_meta = getattr(self, "_xml", {}) + existed_attr_keys: list[str] = [] + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in element: + if e.tag not in existed_attr_keys: + result[e.tag] = _convert_element(e) + + return result + + def copy(self) -> "Model": + return Model(self.__dict__) + + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { + Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: + for base in cls.__bases__: + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore + + @classmethod + def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: + rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access + if rest_field_obj is None: + return attr_name + original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access + if original_tsp_name: + return original_tsp_name + return attr_name + + @classmethod + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: + for v in cls.__dict__.values(): + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v + return None + + @classmethod + def _deserialize(cls, data, exist_discriminators): + if not hasattr(cls, "__mapping__"): + return cls(data) + discriminator = cls._get_discriminator(exist_discriminators) + if discriminator is None: + return cls(data) + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) + + def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: + """Return a dict that can be turned into json using json.dump. + + :keyword bool exclude_readonly: Whether to remove the readonly properties. + :returns: A dict JSON compatible object + :rtype: dict + """ + + result = {} + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] + for k, v in self.items(): + if exclude_readonly and k in readonly_props: # pyright: ignore + continue + is_multipart_file_input = False + try: + is_multipart_file_input = next( + rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k + )._is_multipart_file_input + except StopIteration: + pass + result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) + return result + + @staticmethod + def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: + if v is None or isinstance(v, _Null): + return None + if isinstance(v, (list, tuple, set)): + return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) + if isinstance(v, dict): + return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} + return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v + + +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: list[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: + return ( + isinstance(deserializer, functools.partial) + and isinstance(deserializer.args[0], functools.partial) + and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable + ) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + + # encoded string may be deserialized to sequence + if isinstance(obj, str) and isinstance(deserializer, functools.partial): + # for list[str] + if _is_array_encoded_deserializer(deserializer): + return deserializer(obj) + + # for list[Union[...]] + if isinstance(deserializer.args[0], list): + for sub_deserializer in deserializer.args[0]: + if _is_array_encoded_deserializer(sub_deserializer): + return sub_deserializer(obj) + + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches + annotation: typing.Any, + module: typing.Optional[str], + rf: typing.Optional["_RestField"] = None, +) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + if not annotation: + return None + + # is it a type alias? + if isinstance(annotation, str): + if module is not None: + annotation = _get_type_alias_type(module, annotation) + + # is it a forward ref / in quotes? + if isinstance(annotation, (str, typing.ForwardRef)): + try: + model_name = annotation.__forward_arg__ # type: ignore + except AttributeError: + model_name = annotation + if module is not None: + annotation = _get_model(module, model_name) # type: ignore + + try: + if module and _is_model(annotation): + if rf: + rf._is_model = True + + return functools.partial(_deserialize_model, annotation) # pyright: ignore + except Exception: + pass + + # is it a literal? + try: + if annotation.__origin__ is typing.Literal: # pyright: ignore + return None + except AttributeError: + pass + + # is it optional? + try: + if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore + if rf: + rf._is_optional = True + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) + except AttributeError: + pass + + # is it union? + if getattr(annotation, "__origin__", None) is typing.Union: + # initial ordering is we make `string` the last deserialization option, because it is often them most generic + deserializers = [ + _get_deserialize_callable_from_annotation(arg, module, rf) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore + ] + + return functools.partial(_deserialize_with_union, deserializers) + + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + value_deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[1], module, rf # pyright: ignore + ) + + return functools.partial( + _deserialize_dict, + value_deserializer, + module, + ) + except (AttributeError, IndexError): + pass + try: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + if len(annotation.__args__) > 1: # pyright: ignore + entry_deserializers = [ + _get_deserialize_callable_from_annotation(dt, module, rf) + for dt in annotation.__args__ # pyright: ignore + ] + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) + deserializer = _get_deserialize_callable_from_annotation( + annotation.__args__[0], module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_sequence, deserializer, module) + except (TypeError, IndexError, AttributeError, SyntaxError): + pass + + def _deserialize_default( + deserializer, + obj, + ): + if obj is None: + return obj + try: + return _deserialize_with_callable(deserializer, obj) + except Exception: + pass + return obj + + if get_deserializer(annotation, rf): + return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) + + return functools.partial(_deserialize_default, annotation) + + +def _deserialize_with_callable( + deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], + value: typing.Any, +): # pylint: disable=too-many-return-statements + try: + if value is None or isinstance(value, _Null): + return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): + return deserializer(value.text) if value.text else None + if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): + return deserializer(value.text) if value.text else None + if deserializer is None: + return value + if deserializer in [int, float, bool]: + return deserializer(value) + if isinstance(deserializer, CaseInsensitiveEnumMeta): + try: + return deserializer(value.text if isinstance(value, ET.Element) else value) + except ValueError: + # for unknown value, return raw value + return value.text if isinstance(value, ET.Element) else value + if isinstance(deserializer, type) and issubclass(deserializer, Model): + return deserializer._deserialize(value, []) + return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) + except Exception as e: + raise DeserializationError() from e + + +def _deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + if isinstance(value, PipelineResponse): + value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) + if not isinstance(deserializer, functools.partial): + deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) + return _deserialize_with_callable(deserializer, value) + + +def _failsafe_deserialize( + deserializer: typing.Any, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), module, rf, format) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + except Exception: # pylint: disable=broad-except + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +# pylint: disable=too-many-instance-attributes +class _RestField: + def __init__( + self, + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + is_discriminator: bool = False, + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, + ): + self._type = type + self._rest_name_input = name + self._module: typing.Optional[str] = None + self._is_discriminator = is_discriminator + self._visibility = visibility + self._is_model = False + self._is_optional = False + self._default = default + self._format = format + self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} + self._original_tsp_name = original_tsp_name + + @property + def _class_type(self) -> typing.Any: + result = getattr(self._type, "args", [None])[0] + # type may be wrapped by nested functools.partial so we need to check for that + if isinstance(result, functools.partial): + return getattr(result, "args", [None])[0] + return result + + @property + def _rest_name(self) -> str: + if self._rest_name_input is None: + raise ValueError("Rest name was never set") + return self._rest_name_input + + def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin + # by this point, type and rest_name will have a value bc we default + # them in __new__ of the Model class + # Use _data.get() directly to avoid triggering __getitem__ which clears the cache + item = obj._data.get(self._rest_name) + if item is None: + return item + if self._is_model: + return item + + # For mutable types, we want mutations to directly affect _data + # Check if we've already deserialized this value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + # Return the value from _data directly (it's been deserialized in place) + return obj._data.get(self._rest_name) + + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + + # For mutable types, store the deserialized value back in _data + # so mutations directly affect _data + if isinstance(deserialized, (dict, list, set)): + obj._data[self._rest_name] = deserialized + object.__setattr__(obj, cache_attr, True) # Mark as deserialized + return deserialized + + return deserialized + + def __set__(self, obj: Model, value) -> None: + # Clear the cached deserialized object when setting a new value + cache_attr = f"_deserialized_{self._rest_name}" + if hasattr(obj, cache_attr): + object.__delattr__(obj, cache_attr) + + if value is None: + # we want to wipe out entries if users set attr to None + try: + obj.__delitem__(self._rest_name) + except KeyError: + pass + return + if self._is_model: + if not _is_model(value): + value = _deserialize(self._type, value) + obj.__setitem__(self._rest_name, value) + return + obj.__setitem__(self._rest_name, _serialize(value, self._format)) + + def _get_deserialize_callable_from_annotation( + self, annotation: typing.Any + ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: + return _get_deserialize_callable_from_annotation(annotation, self._module, self) + + +def rest_field( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[dict[str, typing.Any]] = None, + original_tsp_name: typing.Optional[str] = None, +) -> typing.Any: + return _RestField( + name=name, + type=type, + visibility=visibility, + default=default, + format=format, + is_multipart_file_input=is_multipart_file_input, + xml=xml, + original_tsp_name=original_tsp_name, + ) + + +def rest_discriminator( + *, + name: typing.Optional[str] = None, + type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[list[str]] = None, + xml: typing.Optional[dict[str, typing.Any]] = None, +) -> typing.Any: + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: + """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. + + :param dict meta: The metadata dictionary to extract namespace from. + :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. + :rtype: str or None + """ + ns = meta.get("ns") + if ns is None: + ns = meta.get("namespace") + return ns + + +def _resolve_xml_ns( + prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None +) -> typing.Optional[str]: + """Resolve XML namespace for a property, falling back to model namespace when appropriate. + + Checks the property metadata first; if no namespace is found and the model does not declare + an explicit prefix, falls back to the model-level namespace. + + :param dict prop_meta: The property metadata dictionary. + :param dict model_meta: The model metadata dictionary, used as fallback. + :returns: The resolved namespace string, or None. + :rtype: str or None + """ + ns = _get_xml_ns(prop_meta) + if ns is None and model_meta is not None and not model_meta.get("prefix"): + ns = _get_xml_ns(model_meta) + return ns + + +def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: + """Set an XML attribute on an element, handling namespace prefix registration. + + :param ET.Element element: The element to set the attribute on. + :param str name: The default attribute name (wire name). + :param any value: The attribute value. + :param dict prop_meta: The property metadata dictionary. + """ + xml_name = prop_meta.get("name", name) + _attr_ns = _get_xml_ns(prop_meta) + if _attr_ns: + _attr_prefix = prop_meta.get("prefix") + if _attr_prefix: + _safe_register_namespace(_attr_prefix, _attr_ns) + xml_name = "{" + _attr_ns + "}" + xml_name + element.set(xml_name, _get_primitive_type_value(value)) + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, list[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + # When serializing as an array item (parent_meta is set), check if the parent has an + # explicit itemsName. This ensures correct element names for unwrapped arrays (where + # the element tag is the property/items name, not the model type name). + _items_name = parent_meta.get("itemsName") if parent_meta is not None else None + element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) + _model_ns = _get_xml_ns(model_meta) + wrapped_element = _create_xml_element( + element_name, + model_meta.get("prefix"), + _model_ns, + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # Propagate model namespace to properties only for old-style "ns"-keyed models. + # DPG-generated models use the "namespace" key and explicitly declare namespace on + # each property that needs it, so propagation is intentionally skipped for them. + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + _set_xml_attribute(wrapped_element, k, v, prop_meta) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": _dict_ns, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + _items_ns = parent_meta.get("itemsNs") + if _items_ns is None: + _items_ns = _get_xml_ns(parent_meta) + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": _items_ns, + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[dict[str, typing.Any]], +) -> ET.Element: + _meta_ns = _get_xml_ns(meta) if meta else None + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element # type: ignore[no-any-return] + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _safe_register_namespace(prefix: str, ns: str) -> None: + """Register an XML namespace prefix, handling reserved prefix patterns. + + Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for + auto-generated prefixes, causing register_namespace to raise ValueError. + Falls back to directly registering in the internal namespace map. + + :param str prefix: The namespace prefix to register. + :param str ns: The namespace URI. + """ + try: + ET.register_namespace(prefix, ns) + except ValueError: + _ns_map = getattr(ET, "_namespace_map", None) + if _ns_map is not None: + _ns_map[ns] = prefix + + +def _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + _safe_register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: list[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/serialization.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/serialization.py index 6da830e0cf4a..81ec1de5922b 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/serialization.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/serialization.py @@ -3,7 +3,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_version.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_version.py new file mode 100644 index 000000000000..b992dd7e5110 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "12.26.0b1" diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/__init__.py index b4f1dd31c73a..973c8f2ff212 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._azure_file_storage import AzureFileStorage # type: ignore +from ._client import FileClient # type: ignore try: from ._patch import __all__ as _patch_all @@ -22,7 +22,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureFileStorage", + "FileClient", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_azure_file_storage.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py similarity index 63% rename from sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_azure_file_storage.py rename to sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py index 4aac6aa9a1d4..cbe7736f7651 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_azure_file_storage.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py @@ -2,74 +2,51 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, Optional, Union +from typing import Any, Awaitable, TYPE_CHECKING from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .. import models as _models from .._utils.serialization import Deserializer, Serializer -from ._configuration import AzureFileStorageConfiguration +from ._configuration import FileClientConfiguration from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class AzureFileStorage: # pylint: disable=client-accepts-api-version-keyword - """AzureFileStorage. - :ivar service: ServiceOperations operations - :vartype service: azure.storage.fileshare.aio.operations.ServiceOperations - :ivar share: ShareOperations operations - :vartype share: azure.storage.fileshare.aio.operations.ShareOperations +class FileClient: # pylint: disable=client-accepts-api-version-keyword + """Azure File Storage provides scalable file shares in the cloud using SMB and NFS protocols. + :ivar directory: DirectoryOperations operations :vartype directory: azure.storage.fileshare.aio.operations.DirectoryOperations :ivar file: FileOperations operations :vartype file: azure.storage.fileshare.aio.operations.FileOperations - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str + :ivar service: ServiceOperations operations + :vartype service: azure.storage.fileshare.aio.operations.ServiceOperations + :ivar share: ShareOperations operations + :vartype share: azure.storage.fileshare.aio.operations.ShareOperations :param url: The URL of the service account, share, directory or file that is the target of the desired operation. Required. :type url: str - :param base_url: Service URL. Required. Default value is "". - :type base_url: str - :param file_request_intent: Valid value is backup. "backup" Default value is None. - :type file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent - :param allow_trailing_dot: If true, the trailing dot will not be trimmed from the target URI. - Default value is None. - :type allow_trailing_dot: bool - :param allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the source - URI. Default value is None. - :type allow_source_trailing_dot: bool - :keyword file_range_write_from_url: Only update is supported: - Update: Writes the bytes - downloaded from the source url into the specified range. Default value is "update". Note that - overriding this default value may result in unsupported behavior. - :paramtype file_range_write_from_url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-06-06". Default value is "2026-06-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, - version: str, - url: str, - base_url: str = "", - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - allow_trailing_dot: Optional[bool] = None, - allow_source_trailing_dot: Optional[bool] = None, - **kwargs: Any - ) -> None: - self._config = AzureFileStorageConfiguration( - version=version, - url=url, - file_request_intent=file_request_intent, - allow_trailing_dot=allow_trailing_dot, - allow_source_trailing_dot=allow_source_trailing_dot, - **kwargs - ) + def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{url}" + self._config = FileClientConfiguration(url=url, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is None: @@ -88,18 +65,17 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, self._config.http_logging_policy, ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=base_url, policies=_policies, **kwargs) + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - client_models = {k: v for k, v in _models.__dict__.items() if isinstance(v, type)} - self._serialize = Serializer(client_models) - self._deserialize = Deserializer(client_models) + self._serialize = Serializer() + self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) - self.share = ShareOperations(self._client, self._config, self._serialize, self._deserialize) self.directory = DirectoryOperations(self._client, self._config, self._serialize, self._deserialize) self.file = FileOperations(self._client, self._config, self._serialize, self._deserialize) + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.share = ShareOperations(self._client, self._config, self._serialize, self._deserialize) - def _send_request( + def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -107,7 +83,7 @@ def _send_request( >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") - >>> response = await client._send_request(request) + >>> response = await client.send_request(request) For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request @@ -120,7 +96,11 @@ def _send_request( """ request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_configuration.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_configuration.py index bc7aa571cdd4..139d6fcee5c8 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_configuration.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_configuration.py @@ -2,67 +2,50 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any, Literal, Optional, Union +from typing import Any, TYPE_CHECKING from azure.core.pipeline import policies -from .. import models as _models +from .._version import VERSION -VERSION = "unknown" +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class AzureFileStorageConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for AzureFileStorage. +class FileClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for FileClient. Note that all parameters used to create this instance are saved as instance attributes. - :param version: Specifies the version of the operation to use for this request. Required. - :type version: str :param url: The URL of the service account, share, directory or file that is the target of the desired operation. Required. :type url: str - :param file_request_intent: Valid value is backup. "backup" Default value is None. - :type file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent - :param allow_trailing_dot: If true, the trailing dot will not be trimmed from the target URI. - Default value is None. - :type allow_trailing_dot: bool - :param allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the source - URI. Default value is None. - :type allow_source_trailing_dot: bool - :keyword file_range_write_from_url: Only update is supported: - Update: Writes the bytes - downloaded from the source url into the specified range. Default value is "update". Note that - overriding this default value may result in unsupported behavior. - :paramtype file_range_write_from_url: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword version: Specifies the version of the operation to use for this request. Known values + are "2026-06-06". Default value is "2026-06-06". Note that overriding this default value may + result in unsupported behavior. + :paramtype version: str """ - def __init__( - self, - version: str, - url: str, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - allow_trailing_dot: Optional[bool] = None, - allow_source_trailing_dot: Optional[bool] = None, - **kwargs: Any - ) -> None: - file_range_write_from_url: Literal["update"] = kwargs.pop("file_range_write_from_url", "update") + def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + version: str = kwargs.pop("version", "2026-06-06") - if version is None: - raise ValueError("Parameter 'version' must not be None.") if url is None: raise ValueError("Parameter 'url' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") - self.version = version self.url = url - self.file_request_intent = file_request_intent - self.allow_trailing_dot = allow_trailing_dot - self.allow_source_trailing_dot = allow_source_trailing_dot - self.file_range_write_from_url = file_range_write_from_url - kwargs.setdefault("sdk_moniker", "azurefilestorage/{}".format(VERSION)) + self.credential = credential + self.version = version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://storage.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "storage-file-share/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) @@ -76,3 +59,7 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_patch.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_patch.py index f7dd32510333..eb56c0b33775 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_patch.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_patch.py @@ -1,14 +1,133 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +from typing import Any, Optional, TYPE_CHECKING -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +from azure.core import AsyncPipelineClient +from azure.core.pipeline import AsyncPipeline, PipelineRequest +from azure.core.pipeline.policies import SansIOHTTPPolicy + +from ._client import FileClient as GeneratedFileClient +from ._configuration import FileClientConfiguration as GeneratedFileClientConfiguration + +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + + +class RangeHeaderPolicy(SansIOHTTPPolicy): + """Policy that converts the 'Range' header to 'x-ms-range'.""" + + def on_request(self, request: PipelineRequest) -> None: + range_value = request.http_request.headers.pop("Range", None) + if range_value is not None: + request.http_request.headers["x-ms-range"] = range_value + + +class FileClientConfiguration(GeneratedFileClientConfiguration): + """Configuration for FileClient that allows optional credentials. + + This class overrides the generated configuration to allow None credentials + for anonymous access or when a pre-built pipeline handles auth. + + :param url: The URL of the service account, share, directory or file that is the target of the + desired operation. Required. + :type url: str + :param credential: Credential used to authenticate requests to the service. Can be None. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential or None + :keyword version: Specifies the version of the operation to use for this request. + :paramtype version: str + """ + + def __init__(self, url: str, credential: Optional["AsyncTokenCredential"] = None, **kwargs: Any) -> None: + if url is None: + raise ValueError("Parameter 'url' must not be None.") + + version: str = kwargs.pop("version", "2026-06-06") + self.url = url + self.credential = credential + self.version = version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://storage.azure.com/.default"]) + from .._version import VERSION + + kwargs.setdefault("sdk_moniker", "storage-file-share/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + +class AzureFileStorage(GeneratedFileClient): + """Subclass of the generated FileClient that allows optional credentials, + accepts a pre-built pipeline, and injects the RangeHeaderPolicy. + + :param url: The URL of the service account, share, directory or file. + :type url: str + :param credential: Credential used to authenticate requests to the service. + Can be None when a pre-built pipeline is provided. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential or None + :keyword pipeline: A pre-built pipeline to use instead of constructing one. + :paramtype pipeline: ~azure.core.pipeline.Pipeline + :keyword version: Specifies the version of the operation to use for this request. + :paramtype version: str + """ + + def __init__( + self, url: str, credential: Optional["AsyncTokenCredential"] = None, *, pipeline: Any = None, **kwargs: Any + ) -> None: + from azure.core.pipeline import policies + + from .._utils.serialization import Deserializer, Serializer + from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations + + _endpoint = "{url}" + self._config = FileClientConfiguration(url=url, credential=credential, **kwargs) + + if pipeline is not None: + _wrapped_pipeline = AsyncPipeline( + transport=pipeline._transport, + policies=[RangeHeaderPolicy()] + list(pipeline._impl_policies), + ) + self._client = AsyncPipelineClient(base_url=_endpoint, pipeline=_wrapped_pipeline) + else: + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + RangeHeaderPolicy(), + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + + self.service = ServiceOperations(self._client, self._config, self._serialize, self._deserialize) + self.share = ShareOperations(self._client, self._config, self._serialize, self._deserialize) + self.directory = DirectoryOperations(self._client, self._config, self._serialize, self._deserialize) + self.file = FileOperations(self._client, self._config, self._serialize, self._deserialize) + + +# Alias so that `from ._patch import *` overrides the generated FileClient +FileClient = AzureFileStorage + + +__all__: list[str] = ["FileClient"] def patch_sdk(): diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/__init__.py index 092b7efde334..9599ab012f5e 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,20 +12,20 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._service_operations import ServiceOperations # type: ignore -from ._share_operations import ShareOperations # type: ignore -from ._directory_operations import DirectoryOperations # type: ignore -from ._file_operations import FileOperations # type: ignore +from ._operations import DirectoryOperations # type: ignore +from ._operations import FileOperations # type: ignore +from ._operations import ServiceOperations # type: ignore +from ._operations import ShareOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "ServiceOperations", - "ShareOperations", "DirectoryOperations", "FileOperations", + "ServiceOperations", + "ShareOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_directory_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_directory_operations.py deleted file mode 100644 index b83ffd8a6223..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_directory_operations.py +++ /dev/null @@ -1,1077 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Literal, Optional, TypeVar, Union - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._directory_operations import ( - build_create_request, - build_delete_request, - build_force_close_handles_request, - build_get_properties_request, - build_list_files_and_directories_segment_request, - build_list_handles_request, - build_rename_request, - build_set_metadata_request, - build_set_properties_request, -) -from .._configuration import AzureFileStorageConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class DirectoryOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare.aio.AzureFileStorage`'s - :attr:`directory` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureFileStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def create( # pylint: disable=too-many-locals - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - **kwargs: Any - ) -> None: - """Creates a new directory under the specified share or parent directory. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param file_attributes: If specified, the provided file attributes shall be set. Default value: - ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. - Default value is "none". - :type file_attributes: str - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param file_change_time: Change time for the file/directory. Default value: Now. Default value - is None. - :type file_change_time: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :param file_property_semantics: SMB only, default value is New. New will forcefully add the - ARCHIVE attribute flag and alter the permissions specified in x-ms-file-permission to inherit - missing permissions from the parent. Restore will apply changes without further modification. - Known values are: "New" and "Restore". Default value is None. - :type file_property_semantics: str or ~azure.storage.fileshare.models.FilePropertySemantics - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_create_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_attributes=file_attributes, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - file_change_time=file_change_time, - owner=owner, - group=group, - file_mode=file_mode, - file_property_semantics=file_property_semantics, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_properties( - self, sharesnapshot: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any - ) -> None: - """Returns all system properties for the specified directory, and can also be used to check the - existence of a directory. The data returned does not include the files in the directory or any - subdirectories. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_get_properties_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - timeout=timeout, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-server-encrypted") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def delete(self, timeout: Optional[int] = None, **kwargs: Any) -> None: - """Removes the specified empty directory. Note that the directory must be empty before it can be - deleted. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def set_properties( # pylint: disable=too-many-locals - self, - timeout: Optional[int] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - **kwargs: Any - ) -> None: - """Sets properties on the directory. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param file_attributes: If specified, the provided file attributes shall be set. Default value: - ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. - Default value is "none". - :type file_attributes: str - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param file_change_time: Change time for the file/directory. Default value: Now. Default value - is None. - :type file_change_time: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_set_properties_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_attributes=file_attributes, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - file_change_time=file_change_time, - owner=owner, - group=group, - file_mode=file_mode, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def set_metadata( - self, timeout: Optional[int] = None, metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> None: - """Updates user defined metadata for the specified directory. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_set_metadata_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def list_files_and_directories_segment( - self, - prefix: Optional[str] = None, - sharesnapshot: Optional[str] = None, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - include: Optional[list[Union[str, _models.ListFilesIncludeType]]] = None, - include_extended_info: Optional[bool] = None, - **kwargs: Any - ) -> _models.ListFilesAndDirectoriesSegmentResponse: - """Returns a list of files or directories under the specified share or directory. It lists the - contents only for a single level of the directory hierarchy. - - :param prefix: Filters the results to return only entries whose name begins with the specified - prefix. Default value is None. - :type prefix: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param maxresults: Specifies the maximum number of entries to return. If the request does not - specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 - items. Default value is None. - :type maxresults: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param include: Include this parameter to specify one or more datasets to include in the - response. Default value is None. - :type include: list[str or ~azure.storage.fileshare.models.ListFilesIncludeType] - :param include_extended_info: Include extended information. Default value is None. - :type include_extended_info: bool - :return: ListFilesAndDirectoriesSegmentResponse or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ListFilesAndDirectoriesSegmentResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["list"] = kwargs.pop("comp", _params.pop("comp", "list")) - cls: ClsType[_models.ListFilesAndDirectoriesSegmentResponse] = kwargs.pop("cls", None) - - _request = build_list_files_and_directories_segment_request( - url=self._config.url, - version=self._config.version, - prefix=prefix, - sharesnapshot=sharesnapshot, - marker=marker, - maxresults=maxresults, - timeout=timeout, - include=include, - include_extended_info=include_extended_info, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ListFilesAndDirectoriesSegmentResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_handles( - self, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - recursive: Optional[bool] = None, - **kwargs: Any - ) -> _models.ListHandlesResponse: - """Lists handles for directory. - - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param maxresults: Specifies the maximum number of entries to return. If the request does not - specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 - items. Default value is None. - :type maxresults: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param recursive: Specifies operation should apply to the directory specified in the URI, its - files, its subdirectories and their files. Default value is None. - :type recursive: bool - :return: ListHandlesResponse or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ListHandlesResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["listhandles"] = kwargs.pop("comp", _params.pop("comp", "listhandles")) - cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) - - _request = build_list_handles_request( - url=self._config.url, - version=self._config.version, - marker=marker, - maxresults=maxresults, - timeout=timeout, - sharesnapshot=sharesnapshot, - recursive=recursive, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ListHandlesResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def force_close_handles( - self, - handle_id: str, - timeout: Optional[int] = None, - marker: Optional[str] = None, - sharesnapshot: Optional[str] = None, - recursive: Optional[bool] = None, - **kwargs: Any - ) -> None: - """Closes all handles open for given directory. - - :param handle_id: Specifies handle ID opened on the file or directory to be closed. Asterisk - (‘*’) is a wildcard that specifies all handles. Required. - :type handle_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param recursive: Specifies operation should apply to the directory specified in the URI, its - files, its subdirectories and their files. Default value is None. - :type recursive: bool - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["forceclosehandles"] = kwargs.pop("comp", _params.pop("comp", "forceclosehandles")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_force_close_handles_request( - url=self._config.url, - handle_id=handle_id, - version=self._config.version, - timeout=timeout, - marker=marker, - sharesnapshot=sharesnapshot, - recursive=recursive, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-marker"] = self._deserialize("str", response.headers.get("x-ms-marker")) - response_headers["x-ms-number-of-handles-closed"] = self._deserialize( - "int", response.headers.get("x-ms-number-of-handles-closed") - ) - response_headers["x-ms-number-of-handles-failed"] = self._deserialize( - "int", response.headers.get("x-ms-number-of-handles-failed") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def rename( # pylint: disable=too-many-locals - self, - rename_source: str, - timeout: Optional[int] = None, - replace_if_exists: Optional[bool] = None, - ignore_read_only: Optional[bool] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - source_lease_access_conditions: Optional[_models.SourceLeaseAccessConditions] = None, - destination_lease_access_conditions: Optional[_models.DestinationLeaseAccessConditions] = None, - copy_file_smb_info: Optional[_models.CopyFileSmbInfo] = None, - **kwargs: Any - ) -> None: - """Renames a directory. - - :param rename_source: Required. Specifies the URI-style path of the source file, up to 2 KB in - length. Required. - :type rename_source: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param replace_if_exists: Optional. A boolean value for if the destination file already exists, - whether this request will overwrite the file or not. If true, the rename will succeed and will - overwrite the destination file. If not provided or if false and the destination file does - exist, the request will not overwrite the destination file. If provided and the destination - file doesn’t exist, the rename will succeed. Note: This value does not override the - x-ms-file-copy-ignore-read-only header value. Default value is None. - :type replace_if_exists: bool - :param ignore_read_only: Optional. A boolean value that specifies whether the ReadOnly - attribute on a preexisting destination file should be respected. If true, the rename will - succeed, otherwise, a previous file at the destination with the ReadOnly attribute set will - cause the rename to fail. Default value is None. - :type ignore_read_only: bool - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param source_lease_access_conditions: Parameter group. Default value is None. - :type source_lease_access_conditions: - ~azure.storage.fileshare.models.SourceLeaseAccessConditions - :param destination_lease_access_conditions: Parameter group. Default value is None. - :type destination_lease_access_conditions: - ~azure.storage.fileshare.models.DestinationLeaseAccessConditions - :param copy_file_smb_info: Parameter group. Default value is None. - :type copy_file_smb_info: ~azure.storage.fileshare.models.CopyFileSmbInfo - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["rename"] = kwargs.pop("comp", _params.pop("comp", "rename")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _source_lease_id = None - _destination_lease_id = None - _file_attributes = None - _file_creation_time = None - _file_last_write_time = None - _file_change_time = None - if source_lease_access_conditions is not None: - _source_lease_id = source_lease_access_conditions.source_lease_id - if destination_lease_access_conditions is not None: - _destination_lease_id = destination_lease_access_conditions.destination_lease_id - if copy_file_smb_info is not None: - _file_attributes = copy_file_smb_info.file_attributes - _file_change_time = copy_file_smb_info.file_change_time - _file_creation_time = copy_file_smb_info.file_creation_time - _file_last_write_time = copy_file_smb_info.file_last_write_time - - _request = build_rename_request( - url=self._config.url, - rename_source=rename_source, - version=self._config.version, - timeout=timeout, - replace_if_exists=replace_if_exists, - ignore_read_only=ignore_read_only, - source_lease_id=_source_lease_id, - destination_lease_id=_destination_lease_id, - file_attributes=_file_attributes, - file_creation_time=_file_creation_time, - file_last_write_time=_file_last_write_time, - file_change_time=_file_change_time, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - metadata=metadata, - allow_trailing_dot=self._config.allow_trailing_dot, - allow_source_trailing_dot=self._config.allow_source_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_file_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_file_operations.py deleted file mode 100644 index 1f6bc63e53c0..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_file_operations.py +++ /dev/null @@ -1,2605 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, AsyncIterator, Callable, IO, Literal, Optional, TypeVar, Union - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._file_operations import ( - build_abort_copy_request, - build_acquire_lease_request, - build_break_lease_request, - build_change_lease_request, - build_create_hard_link_request, - build_create_request, - build_create_symbolic_link_request, - build_delete_request, - build_download_request, - build_force_close_handles_request, - build_get_properties_request, - build_get_range_list_request, - build_get_symbolic_link_request, - build_list_handles_request, - build_release_lease_request, - build_rename_request, - build_set_http_headers_request, - build_set_metadata_request, - build_start_copy_request, - build_upload_range_from_url_request, - build_upload_range_request, -) -from .._configuration import AzureFileStorageConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class FileOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare.aio.AzureFileStorage`'s - :attr:`file` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureFileStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def create( # pylint: disable=too-many-locals - self, - file_content_length: int, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, - content_md5: Optional[bytes] = None, - file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - content_length: Optional[int] = None, - structured_body_type: Optional[str] = None, - structured_content_length: Optional[int] = None, - file_http_headers: Optional[_models.FileHTTPHeaders] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - optionalbody: Optional[IO[bytes]] = None, - **kwargs: Any - ) -> None: - """Creates a new file or replaces a file. Can also initialize the file with content. - - :param file_content_length: Specifies the maximum size for the file, up to 4 TB. Required. - :type file_content_length: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param file_attributes: If specified, the provided file attributes shall be set. Default value: - ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. - Default value is "none". - :type file_attributes: str - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param file_change_time: Change time for the file/directory. Default value: Now. Default value - is None. - :type file_change_time: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :param nfs_file_type: Optional, NFS only. Type of the file or directory. Known values are: - "Regular", "Directory", and "SymLink". Default value is None. - :type nfs_file_type: str or ~azure.storage.fileshare.models.NfsFileType - :param content_md5: An MD5 hash of the content. This hash is used to verify the integrity of - the data during transport. When the Content-MD5 header is specified, the File service compares - the hash of the content that has arrived with the header value that was sent. If the two hashes - do not match, the operation will fail with error code 400 (Bad Request). Default value is None. - :type content_md5: bytes - :param file_property_semantics: SMB only, default value is New. New will forcefully add the - ARCHIVE attribute flag and alter the permissions specified in x-ms-file-permission to inherit - missing permissions from the parent. Restore will apply changes without further modification. - Known values are: "New" and "Restore". Default value is None. - :type file_property_semantics: str or ~azure.storage.fileshare.models.FilePropertySemantics - :param content_length: Specifies the number of bytes being transmitted in the request body. - When the x-ms-write header is set to clear, the value of this header must be set to zero. - Default value is None. - :type content_length: int - :param structured_body_type: Required if the request body is a structured message. Specifies - the message schema version and properties. Default value is None. - :type structured_body_type: str - :param structured_content_length: Required if the request body is a structured message. - Specifies the length of the blob/file content inside the message body. Will always be smaller - than Content-Length. Default value is None. - :type structured_content_length: int - :param file_http_headers: Parameter group. Default value is None. - :type file_http_headers: ~azure.storage.fileshare.models.FileHTTPHeaders - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :param optionalbody: Initial data. Default value is None. - :type optionalbody: IO[bytes] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - file_type_constant: Literal["file"] = kwargs.pop("file_type_constant", _headers.pop("x-ms-type", "file")) - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/octet-stream") - ) - content_type = content_type if optionalbody else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _file_content_type = None - _file_content_encoding = None - _file_content_language = None - _file_cache_control = None - _file_content_md5 = None - _file_content_disposition = None - _lease_id = None - if file_http_headers is not None: - _file_cache_control = file_http_headers.file_cache_control - _file_content_disposition = file_http_headers.file_content_disposition - _file_content_encoding = file_http_headers.file_content_encoding - _file_content_language = file_http_headers.file_content_language - _file_content_md5 = file_http_headers.file_content_md5 - _file_content_type = file_http_headers.file_content_type - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - _content = optionalbody - - _request = build_create_request( - url=self._config.url, - file_content_length=file_content_length, - version=self._config.version, - timeout=timeout, - file_content_type=_file_content_type, - file_content_encoding=_file_content_encoding, - file_content_language=_file_content_language, - file_cache_control=_file_cache_control, - file_content_md5=_file_content_md5, - file_content_disposition=_file_content_disposition, - metadata=metadata, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_attributes=file_attributes, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - file_change_time=file_change_time, - lease_id=_lease_id, - owner=owner, - group=group, - file_mode=file_mode, - nfs_file_type=nfs_file_type, - content_md5=content_md5, - file_property_semantics=file_property_semantics, - content_length=content_length, - structured_body_type=structured_body_type, - structured_content_length=structured_content_length, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - file_type_constant=file_type_constant, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) - response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) - response_headers["x-ms-structured-body"] = self._deserialize( - "str", response.headers.get("x-ms-structured-body") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def download( - self, - timeout: Optional[int] = None, - range: Optional[str] = None, - range_get_content_md5: Optional[bool] = None, - structured_body_type: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - """Reads or downloads a file from the system, including its metadata and properties. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param range: Return file data only from the specified byte range. Default value is None. - :type range: str - :param range_get_content_md5: When this header is set to true and specified together with the - Range header, the service returns the MD5 hash for the range, as long as the range is less than - or equal to 4 MB in size. Default value is None. - :type range_get_content_md5: bool - :param structured_body_type: Specifies the response content should be returned as a structured - message and specifies the message schema version and properties. Default value is None. - :type structured_body_type: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: AsyncIterator[bytes] or the result of cls(response) - :rtype: AsyncIterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_download_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - range=range, - range_get_content_md5=range_get_content_md5, - structured_body_type=structured_body_type, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) - response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["Content-Range"] = self._deserialize("str", response.headers.get("Content-Range")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) - response_headers["Content-Encoding"] = self._deserialize("str", response.headers.get("Content-Encoding")) - response_headers["Cache-Control"] = self._deserialize("str", response.headers.get("Cache-Control")) - response_headers["Content-Disposition"] = self._deserialize("str", response.headers.get("Content-Disposition")) - response_headers["Content-Language"] = self._deserialize("str", response.headers.get("Content-Language")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Accept-Ranges"] = self._deserialize("str", response.headers.get("Accept-Ranges")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-copy-completion-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-copy-completion-time") - ) - response_headers["x-ms-copy-status-description"] = self._deserialize( - "str", response.headers.get("x-ms-copy-status-description") - ) - response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) - response_headers["x-ms-copy-progress"] = self._deserialize("str", response.headers.get("x-ms-copy-progress")) - response_headers["x-ms-copy-source"] = self._deserialize("str", response.headers.get("x-ms-copy-source")) - response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) - response_headers["x-ms-content-md5"] = self._deserialize("bytearray", response.headers.get("x-ms-content-md5")) - response_headers["x-ms-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-server-encrypted") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) - response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) - response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) - response_headers["x-ms-structured-body"] = self._deserialize( - "str", response.headers.get("x-ms-structured-body") - ) - response_headers["x-ms-structured-content-length"] = self._deserialize( - "int", response.headers.get("x-ms-structured-content-length") - ) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_properties( - self, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Returns all user-defined metadata, standard HTTP properties, and system properties for the - file. It does not return the content of the file. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_properties_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - timeout=timeout, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) - response_headers["x-ms-type"] = self._deserialize("str", response.headers.get("x-ms-type")) - response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) - response_headers["Content-Encoding"] = self._deserialize("str", response.headers.get("Content-Encoding")) - response_headers["Cache-Control"] = self._deserialize("str", response.headers.get("Cache-Control")) - response_headers["Content-Disposition"] = self._deserialize("str", response.headers.get("Content-Disposition")) - response_headers["Content-Language"] = self._deserialize("str", response.headers.get("Content-Language")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-copy-completion-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-copy-completion-time") - ) - response_headers["x-ms-copy-status-description"] = self._deserialize( - "str", response.headers.get("x-ms-copy-status-description") - ) - response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) - response_headers["x-ms-copy-progress"] = self._deserialize("str", response.headers.get("x-ms-copy-progress")) - response_headers["x-ms-copy-source"] = self._deserialize("str", response.headers.get("x-ms-copy-source")) - response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) - response_headers["x-ms-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-server-encrypted") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) - response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) - response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def delete( - self, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """removes the file from the storage account. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_delete_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def set_http_headers( # pylint: disable=too-many-locals - self, - timeout: Optional[int] = None, - file_content_length: Optional[int] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - file_http_headers: Optional[_models.FileHTTPHeaders] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Sets HTTP headers on the file. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param file_content_length: Resizes a file to the specified size. If the specified byte value - is less than the current size of the file, then all ranges above the specified byte value are - cleared. Default value is None. - :type file_content_length: int - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param file_attributes: If specified, the provided file attributes shall be set. Default value: - ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. - Default value is "none". - :type file_attributes: str - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param file_change_time: Change time for the file/directory. Default value: Now. Default value - is None. - :type file_change_time: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :param file_http_headers: Parameter group. Default value is None. - :type file_http_headers: ~azure.storage.fileshare.models.FileHTTPHeaders - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _file_content_type = None - _file_content_encoding = None - _file_content_language = None - _file_cache_control = None - _file_content_md5 = None - _file_content_disposition = None - _lease_id = None - if file_http_headers is not None: - _file_cache_control = file_http_headers.file_cache_control - _file_content_disposition = file_http_headers.file_content_disposition - _file_content_encoding = file_http_headers.file_content_encoding - _file_content_language = file_http_headers.file_content_language - _file_content_md5 = file_http_headers.file_content_md5 - _file_content_type = file_http_headers.file_content_type - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_set_http_headers_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_content_length=file_content_length, - file_content_type=_file_content_type, - file_content_encoding=_file_content_encoding, - file_content_language=_file_content_language, - file_cache_control=_file_cache_control, - file_content_md5=_file_content_md5, - file_content_disposition=_file_content_disposition, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_attributes=file_attributes, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - file_change_time=file_change_time, - lease_id=_lease_id, - owner=owner, - group=group, - file_mode=file_mode, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def set_metadata( - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Updates user-defined metadata for the specified file. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_set_metadata_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def acquire_lease( - self, - timeout: Optional[int] = None, - duration: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """[Update] The Lease File operation establishes and manages a lock on a file for write and delete - operations. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param duration: Specifies the duration of the lease, in seconds, or negative one (-1) for a - lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease - duration cannot be changed using renew or change. Default value is None. - :type duration: int - :param proposed_lease_id: Proposed lease ID, in a GUID string format. The File service returns - 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid - Constructor (String) for a list of valid GUID string formats. Default value is None. - :type proposed_lease_id: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_acquire_lease_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - duration=duration, - proposed_lease_id=proposed_lease_id, - request_id_parameter=request_id_parameter, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def release_lease( - self, lease_id: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any - ) -> None: - """[Update] The Lease File operation establishes and manages a lock on a file for write and delete - operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_release_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - request_id_parameter=request_id_parameter, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def change_lease( - self, - lease_id: str, - timeout: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """[Update] The Lease File operation establishes and manages a lock on a file for write and delete - operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param proposed_lease_id: Proposed lease ID, in a GUID string format. The File service returns - 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid - Constructor (String) for a list of valid GUID string formats. Default value is None. - :type proposed_lease_id: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_change_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - proposed_lease_id=proposed_lease_id, - request_id_parameter=request_id_parameter, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def break_lease( - self, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """[Update] The Lease File operation establishes and manages a lock on a file for write and delete - operations. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_break_lease_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - request_id_parameter=request_id_parameter, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def upload_range( # pylint: disable=too-many-locals - self, - range: str, - content_length: int, - timeout: Optional[int] = None, - file_range_write: Union[str, _models.FileRangeWriteType] = "update", - content_md5: Optional[bytes] = None, - file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, - structured_body_type: Optional[str] = None, - structured_content_length: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - optionalbody: Optional[IO[bytes]] = None, - **kwargs: Any - ) -> None: - """Upload a range of bytes to a file. - - :param range: Specifies the range of bytes to be written. Both the start and end of the range - must be specified. For an update operation, the range can be up to 4 MB in size. For a clear - operation, the range can be up to the value of the file's full size. The File service accepts - only a single byte range for the Range and 'x-ms-range' headers, and the byte range must be - specified in the following format: bytes=startByte-endByte. Required. - :type range: str - :param content_length: Specifies the number of bytes being transmitted in the request body. - When the x-ms-write header is set to clear, the value of this header must be set to zero. - Required. - :type content_length: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param file_range_write: Specify one of the following options: - Update: Writes the bytes - specified by the request body into the specified range. The Range and Content-Length headers - must match to perform the update. - Clear: Clears the specified range and releases the space - used in storage for that range. To clear a range, set the Content-Length header to zero, and - set the Range header to a value that indicates the range to clear, up to maximum file size. - Known values are: "update" and "clear". Default value is "update". - :type file_range_write: str or ~azure.storage.fileshare.models.FileRangeWriteType - :param content_md5: An MD5 hash of the content. This hash is used to verify the integrity of - the data during transport. When the Content-MD5 header is specified, the File service compares - the hash of the content that has arrived with the header value that was sent. If the two hashes - do not match, the operation will fail with error code 400 (Bad Request). Default value is None. - :type content_md5: bytes - :param file_last_written_mode: If the file last write time should be preserved or overwritten. - Known values are: "Now" and "Preserve". Default value is None. - :type file_last_written_mode: str or ~azure.storage.fileshare.models.FileLastWrittenMode - :param structured_body_type: Required if the request body is a structured message. Specifies - the message schema version and properties. Default value is None. - :type structured_body_type: str - :param structured_content_length: Required if the request body is a structured message. - Specifies the length of the blob/file content inside the message body. Will always be smaller - than Content-Length. Default value is None. - :type structured_content_length: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :param optionalbody: Initial data. Default value is None. - :type optionalbody: IO[bytes] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["range"] = kwargs.pop("comp", _params.pop("comp", "range")) - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/octet-stream") - ) - content_type = content_type if optionalbody else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - _content = optionalbody - - _request = build_upload_range_request( - url=self._config.url, - range=range, - content_length=content_length, - version=self._config.version, - timeout=timeout, - file_range_write=file_range_write, - content_md5=content_md5, - lease_id=_lease_id, - file_last_written_mode=file_last_written_mode, - structured_body_type=structured_body_type, - structured_content_length=structured_content_length, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-structured-body"] = self._deserialize( - "str", response.headers.get("x-ms-structured-body") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def upload_range_from_url( - self, - range: str, - copy_source: str, - content_length: int, - timeout: Optional[int] = None, - source_range: Optional[str] = None, - source_content_crc64: Optional[bytes] = None, - copy_source_authorization: Optional[str] = None, - file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, - source_modified_access_conditions: Optional[_models.SourceModifiedAccessConditions] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Upload a range of bytes to a file where the contents are read from a URL. - - :param range: Writes data to the specified byte range in the file. Required. - :type range: str - :param copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. To copy - a file to another file within the same storage account, you may use Shared Key to authenticate - the source file. If you are copying a file from another storage account, or if you are copying - a blob from the same storage account or another storage account, then you must authenticate the - source file or blob using a shared access signature. If the source is a public blob, no - authentication is required to perform the copy operation. A file in a share snapshot can also - be specified as a copy source. Required. - :type copy_source: str - :param content_length: Specifies the number of bytes being transmitted in the request body. - When the x-ms-write header is set to clear, the value of this header must be set to zero. - Required. - :type content_length: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param source_range: Bytes of source data in the specified range. Default value is None. - :type source_range: str - :param source_content_crc64: Specify the crc64 calculated for the range of bytes that must be - read from the copy source. Default value is None. - :type source_content_crc64: bytes - :param copy_source_authorization: Only Bearer type is supported. Credentials should be a valid - OAuth access token to copy source. Default value is None. - :type copy_source_authorization: str - :param file_last_written_mode: If the file last write time should be preserved or overwritten. - Known values are: "Now" and "Preserve". Default value is None. - :type file_last_written_mode: str or ~azure.storage.fileshare.models.FileLastWrittenMode - :param source_modified_access_conditions: Parameter group. Default value is None. - :type source_modified_access_conditions: - ~azure.storage.fileshare.models.SourceModifiedAccessConditions - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["range"] = kwargs.pop("comp", _params.pop("comp", "range")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _source_if_match_crc64 = None - _source_if_none_match_crc64 = None - _lease_id = None - if source_modified_access_conditions is not None: - _source_if_match_crc64 = source_modified_access_conditions.source_if_match_crc64 - _source_if_none_match_crc64 = source_modified_access_conditions.source_if_none_match_crc64 - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_upload_range_from_url_request( - url=self._config.url, - range=range, - copy_source=copy_source, - content_length=content_length, - version=self._config.version, - timeout=timeout, - source_range=source_range, - source_content_crc64=source_content_crc64, - source_if_match_crc64=_source_if_match_crc64, - source_if_none_match_crc64=_source_if_none_match_crc64, - lease_id=_lease_id, - copy_source_authorization=copy_source_authorization, - file_last_written_mode=file_last_written_mode, - allow_trailing_dot=self._config.allow_trailing_dot, - allow_source_trailing_dot=self._config.allow_source_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - file_range_write_from_url=self._config.file_range_write_from_url, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-content-crc64"] = self._deserialize( - "bytearray", response.headers.get("x-ms-content-crc64") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_range_list( - self, - sharesnapshot: Optional[str] = None, - prevsharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - range: Optional[str] = None, - support_rename: Optional[bool] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> _models.ShareFileRangeList: - """Returns the list of valid ranges for a file. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param prevsharesnapshot: The previous snapshot parameter is an opaque DateTime value that, - when present, specifies the previous snapshot. Default value is None. - :type prevsharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param range: Specifies the range of bytes over which to list ranges, inclusively. Default - value is None. - :type range: str - :param support_rename: This header is allowed only when PrevShareSnapshot query parameter is - set. Determines whether the changed ranges for a file that has been renamed or moved between - the target snapshot (or the live file) and the previous snapshot should be listed. If the value - is true, the valid changed ranges for the file will be returned. If the value is false, the - operation will result in a failure with 409 (Conflict) response. The default value is false. - Default value is None. - :type support_rename: bool - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: ShareFileRangeList or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ShareFileRangeList - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["rangelist"] = kwargs.pop("comp", _params.pop("comp", "rangelist")) - cls: ClsType[_models.ShareFileRangeList] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_range_list_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - prevsharesnapshot=prevsharesnapshot, - timeout=timeout, - range=range, - lease_id=_lease_id, - support_rename=support_rename, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["x-ms-content-length"] = self._deserialize("int", response.headers.get("x-ms-content-length")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ShareFileRangeList", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def start_copy( # pylint: disable=too-many-locals - self, - copy_source: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - file_mode_copy_mode: Optional[Union[str, _models.ModeCopyMode]] = None, - file_owner_copy_mode: Optional[Union[str, _models.OwnerCopyMode]] = None, - copy_file_smb_info: Optional[_models.CopyFileSmbInfo] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Copies a blob or file to a destination file within the storage account. - - :param copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. To copy - a file to another file within the same storage account, you may use Shared Key to authenticate - the source file. If you are copying a file from another storage account, or if you are copying - a blob from the same storage account or another storage account, then you must authenticate the - source file or blob using a shared access signature. If the source is a public blob, no - authentication is required to perform the copy operation. A file in a share snapshot can also - be specified as a copy source. Required. - :type copy_source: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :param file_mode_copy_mode: NFS only. Applicable only when the copy source is a File. - Determines the copy behavior of the mode bits of the file. source: The mode on the destination - file is copied from the source file. override: The mode on the destination file is determined - via the x-ms-mode header. Known values are: "source" and "override". Default value is None. - :type file_mode_copy_mode: str or ~azure.storage.fileshare.models.ModeCopyMode - :param file_owner_copy_mode: NFS only. Determines the copy behavior of the owner user - identifier (UID) and group identifier (GID) of the file. source: The owner user identifier - (UID) and group identifier (GID) on the destination file is copied from the source file. - override: The owner user identifier (UID) and group identifier (GID) on the destination file is - determined via the x-ms-owner and x-ms-group headers. Known values are: "source" and - "override". Default value is None. - :type file_owner_copy_mode: str or ~azure.storage.fileshare.models.OwnerCopyMode - :param copy_file_smb_info: Parameter group. Default value is None. - :type copy_file_smb_info: ~azure.storage.fileshare.models.CopyFileSmbInfo - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _file_permission_copy_mode = None - _ignore_read_only = None - _file_attributes = None - _file_creation_time = None - _file_last_write_time = None - _file_change_time = None - _set_archive_attribute = None - _lease_id = None - if copy_file_smb_info is not None: - _file_attributes = copy_file_smb_info.file_attributes - _file_change_time = copy_file_smb_info.file_change_time - _file_creation_time = copy_file_smb_info.file_creation_time - _file_last_write_time = copy_file_smb_info.file_last_write_time - _file_permission_copy_mode = copy_file_smb_info.file_permission_copy_mode - _ignore_read_only = copy_file_smb_info.ignore_read_only - _set_archive_attribute = copy_file_smb_info.set_archive_attribute - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_start_copy_request( - url=self._config.url, - copy_source=copy_source, - version=self._config.version, - timeout=timeout, - metadata=metadata, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_permission_copy_mode=_file_permission_copy_mode, - ignore_read_only=_ignore_read_only, - file_attributes=_file_attributes, - file_creation_time=_file_creation_time, - file_last_write_time=_file_last_write_time, - file_change_time=_file_change_time, - set_archive_attribute=_set_archive_attribute, - lease_id=_lease_id, - owner=owner, - group=group, - file_mode=file_mode, - file_mode_copy_mode=file_mode_copy_mode, - file_owner_copy_mode=file_owner_copy_mode, - allow_trailing_dot=self._config.allow_trailing_dot, - allow_source_trailing_dot=self._config.allow_source_trailing_dot, - file_request_intent=self._config.file_request_intent, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) - response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def abort_copy( - self, - copy_id: str, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Aborts a pending Copy File operation, and leaves a destination file with zero length and full - metadata. - - :param copy_id: The copy identifier provided in the x-ms-copy-id header of the original Copy - File operation. Required. - :type copy_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["copy"] = kwargs.pop("comp", _params.pop("comp", "copy")) - copy_action_abort_constant: Literal["abort"] = kwargs.pop( - "copy_action_abort_constant", _headers.pop("x-ms-copy-action", "abort") - ) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_abort_copy_request( - url=self._config.url, - copy_id=copy_id, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - copy_action_abort_constant=copy_action_abort_constant, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def list_handles( - self, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - **kwargs: Any - ) -> _models.ListHandlesResponse: - """Lists handles for file. - - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param maxresults: Specifies the maximum number of entries to return. If the request does not - specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 - items. Default value is None. - :type maxresults: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :return: ListHandlesResponse or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ListHandlesResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["listhandles"] = kwargs.pop("comp", _params.pop("comp", "listhandles")) - cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) - - _request = build_list_handles_request( - url=self._config.url, - version=self._config.version, - marker=marker, - maxresults=maxresults, - timeout=timeout, - sharesnapshot=sharesnapshot, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ListHandlesResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def force_close_handles( - self, - handle_id: str, - timeout: Optional[int] = None, - marker: Optional[str] = None, - sharesnapshot: Optional[str] = None, - **kwargs: Any - ) -> None: - """Closes all handles open for given file. - - :param handle_id: Specifies handle ID opened on the file or directory to be closed. Asterisk - (‘*’) is a wildcard that specifies all handles. Required. - :type handle_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["forceclosehandles"] = kwargs.pop("comp", _params.pop("comp", "forceclosehandles")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_force_close_handles_request( - url=self._config.url, - handle_id=handle_id, - version=self._config.version, - timeout=timeout, - marker=marker, - sharesnapshot=sharesnapshot, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-marker"] = self._deserialize("str", response.headers.get("x-ms-marker")) - response_headers["x-ms-number-of-handles-closed"] = self._deserialize( - "int", response.headers.get("x-ms-number-of-handles-closed") - ) - response_headers["x-ms-number-of-handles-failed"] = self._deserialize( - "int", response.headers.get("x-ms-number-of-handles-failed") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def rename( # pylint: disable=too-many-locals - self, - rename_source: str, - timeout: Optional[int] = None, - replace_if_exists: Optional[bool] = None, - ignore_read_only: Optional[bool] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - source_lease_access_conditions: Optional[_models.SourceLeaseAccessConditions] = None, - destination_lease_access_conditions: Optional[_models.DestinationLeaseAccessConditions] = None, - copy_file_smb_info: Optional[_models.CopyFileSmbInfo] = None, - file_http_headers: Optional[_models.FileHTTPHeaders] = None, - **kwargs: Any - ) -> None: - """Renames a file. - - :param rename_source: Required. Specifies the URI-style path of the source file, up to 2 KB in - length. Required. - :type rename_source: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param replace_if_exists: Optional. A boolean value for if the destination file already exists, - whether this request will overwrite the file or not. If true, the rename will succeed and will - overwrite the destination file. If not provided or if false and the destination file does - exist, the request will not overwrite the destination file. If provided and the destination - file doesn’t exist, the rename will succeed. Note: This value does not override the - x-ms-file-copy-ignore-read-only header value. Default value is None. - :type replace_if_exists: bool - :param ignore_read_only: Optional. A boolean value that specifies whether the ReadOnly - attribute on a preexisting destination file should be respected. If true, the rename will - succeed, otherwise, a previous file at the destination with the ReadOnly attribute set will - cause the rename to fail. Default value is None. - :type ignore_read_only: bool - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param source_lease_access_conditions: Parameter group. Default value is None. - :type source_lease_access_conditions: - ~azure.storage.fileshare.models.SourceLeaseAccessConditions - :param destination_lease_access_conditions: Parameter group. Default value is None. - :type destination_lease_access_conditions: - ~azure.storage.fileshare.models.DestinationLeaseAccessConditions - :param copy_file_smb_info: Parameter group. Default value is None. - :type copy_file_smb_info: ~azure.storage.fileshare.models.CopyFileSmbInfo - :param file_http_headers: Parameter group. Default value is None. - :type file_http_headers: ~azure.storage.fileshare.models.FileHTTPHeaders - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["rename"] = kwargs.pop("comp", _params.pop("comp", "rename")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _source_lease_id = None - _destination_lease_id = None - _file_attributes = None - _file_creation_time = None - _file_last_write_time = None - _file_change_time = None - _file_content_type = None - if source_lease_access_conditions is not None: - _source_lease_id = source_lease_access_conditions.source_lease_id - if destination_lease_access_conditions is not None: - _destination_lease_id = destination_lease_access_conditions.destination_lease_id - if copy_file_smb_info is not None: - _file_attributes = copy_file_smb_info.file_attributes - _file_change_time = copy_file_smb_info.file_change_time - _file_creation_time = copy_file_smb_info.file_creation_time - _file_last_write_time = copy_file_smb_info.file_last_write_time - if file_http_headers is not None: - _file_content_type = file_http_headers.file_content_type - - _request = build_rename_request( - url=self._config.url, - rename_source=rename_source, - version=self._config.version, - timeout=timeout, - replace_if_exists=replace_if_exists, - ignore_read_only=ignore_read_only, - source_lease_id=_source_lease_id, - destination_lease_id=_destination_lease_id, - file_attributes=_file_attributes, - file_creation_time=_file_creation_time, - file_last_write_time=_file_last_write_time, - file_change_time=_file_change_time, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - metadata=metadata, - file_content_type=_file_content_type, - allow_trailing_dot=self._config.allow_trailing_dot, - allow_source_trailing_dot=self._config.allow_source_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def create_symbolic_link( - self, - link_text: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_creation_time: str = "now", - file_last_write_time: str = "now", - request_id_parameter: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Creates a symbolic link. - - :param link_text: NFS only. Required. The path to the original file, the symbolic link is - pointing to. The path is of type string which is not resolved and is stored as is. The path can - be absolute path or the relative path depending on the content stored in the symbolic link - file. Required. - :type link_text: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["symboliclink"] = kwargs.pop("restype", _params.pop("restype", "symboliclink")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_create_symbolic_link_request( - url=self._config.url, - link_text=link_text, - version=self._config.version, - timeout=timeout, - metadata=metadata, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - request_id_parameter=request_id_parameter, - lease_id=_lease_id, - owner=owner, - group=group, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_symbolic_link( - self, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """get_symbolic_link. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["symboliclink"] = kwargs.pop("restype", _params.pop("restype", "symboliclink")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_get_symbolic_link_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-link-text"] = self._deserialize("str", response.headers.get("x-ms-link-text")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def create_hard_link( - self, - target_file: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Creates a hard link. - - :param target_file: NFS only. Required. Specifies the path of the target file to which the link - will be created, up to 2 KiB in length. It should be full path of the target from the root.The - target file must be in the same share and hence the same storage account. Required. - :type target_file: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["hardlink"] = kwargs.pop("restype", _params.pop("restype", "hardlink")) - file_type_constant: Literal["file"] = kwargs.pop("file_type_constant", _headers.pop("x-ms-type", "file")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_create_hard_link_request( - url=self._config.url, - target_file=target_file, - version=self._config.version, - timeout=timeout, - request_id_parameter=request_id_parameter, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - file_type_constant=file_type_constant, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_operations.py new file mode 100644 index 000000000000..79d9adc0c19d --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_operations.py @@ -0,0 +1,5909 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, AsyncIterator, Callable, IO, Literal, Optional, TypeVar, Union, overload + +from azure.core import AsyncPipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest +from azure.core.tracing.decorator_async import distributed_trace_async +from azure.core.utils import case_insensitive_dict + +from ... import models as _models +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _deserialize_xml, _failsafe_deserialize_xml, _get_element +from ..._utils.serialization import Deserializer, Serializer +from ...operations._operations import ( + build_directory_create_request, + build_directory_delete_request, + build_directory_force_close_handles_request, + build_directory_get_properties_request, + build_directory_list_files_and_directories_segment_request, + build_directory_list_handles_request, + build_directory_rename_request, + build_directory_set_metadata_request, + build_directory_set_properties_request, + build_file_abort_copy_request, + build_file_acquire_lease_request, + build_file_break_lease_request, + build_file_change_lease_request, + build_file_create_hard_link_request, + build_file_create_request, + build_file_create_symbolic_link_request, + build_file_delete_request, + build_file_download_request, + build_file_force_close_handles_request, + build_file_get_properties_request, + build_file_get_range_list_request, + build_file_get_symbolic_link_request, + build_file_list_handles_request, + build_file_release_lease_request, + build_file_rename_request, + build_file_set_http_headers_request, + build_file_set_metadata_request, + build_file_start_copy_request, + build_file_upload_range_from_url_request, + build_file_upload_range_request, + build_service_get_properties_request, + build_service_get_user_delegation_key_request, + build_service_list_shares_segment_request, + build_service_set_properties_request, + build_share_acquire_lease_request, + build_share_break_lease_request, + build_share_change_lease_request, + build_share_create_permission_request, + build_share_create_request, + build_share_create_snapshot_request, + build_share_delete_request, + build_share_get_access_policy_request, + build_share_get_permission_request, + build_share_get_properties_request, + build_share_get_statistics_request, + build_share_release_lease_request, + build_share_renew_lease_request, + build_share_restore_request, + build_share_set_access_policy_request, + build_share_set_metadata_request, + build_share_set_properties_request, +) +from .._configuration import FileClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] + + +class DirectoryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.aio.FileClient`'s + :attr:`directory` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FileClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def create( # pylint: disable=too-many-locals + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Creates a new directory under the specified share or parent directory. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_permission: If specified the permission (security descriptor) shall be set for + the directory/file. This header can be used if Permission size is <= 8KB, else + x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as + input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or + x-ms-file-permission-key should be specified. Default value is None. + :paramtype file_permission: str + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default + value is None. + :paramtype file_permission_key: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value: 'Archive' for file and 'Directory' for directory. 'None' can also be specified as + default. Default value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file/directory. Default value: Now. + Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_change_time: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :keyword file_property_semantics: SMB only. Default value is New. Known values are: "New" and + "Restore". Default value is None. + :paramtype file_property_semantics: str or + ~azure.storage.fileshare.models.FilePropertySemantics + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_create_request( + timeout=timeout, + metadata=metadata, + file_permission=file_permission, + file_permission_key=file_permission_key, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission_format=file_permission_format, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + file_property_semantics=file_property_semantics, + allow_trailing_dot=allow_trailing_dot, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_properties( + self, + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Returns all system properties for the specified directory, and can also be used to check the + existence of a directory. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_get_properties_request( + sharesnapshot=sharesnapshot, + timeout=timeout, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-server-encrypted") + ) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def delete( + self, + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Removes the specified empty directory. Note that the directory must be empty before it can be + deleted. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_delete_request( + timeout=timeout, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def set_properties( # pylint: disable=too-many-locals + self, + *, + timeout: Optional[int] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + **kwargs: Any + ) -> None: + """Sets properties for the specified directory. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_permission: If specified the permission (security descriptor) shall be set for + the directory/file. This header can be used if Permission size is <= 8KB, else + x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as + input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or + x-ms-file-permission-key should be specified. Default value is None. + :paramtype file_permission: str + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default + value is None. + :paramtype file_permission_key: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value: 'Archive' for file and 'Directory' for directory. 'None' can also be specified as + default. Default value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file/directory. Default value: Now. + Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_change_time: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_set_properties_request( + timeout=timeout, + file_permission=file_permission, + file_permission_key=file_permission_key, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission_format=file_permission_format, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def set_metadata( + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Sets one or more user-defined name-value pairs for the specified directory. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_set_metadata_request( + timeout=timeout, + metadata=metadata, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def list_files_and_directories_segment( + self, + *, + prefix: Optional[str] = None, + sharesnapshot: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + include: Optional[list[Union[str, _models.ListFilesIncludeType]]] = None, + timeout: Optional[int] = None, + include_extended_info: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.ListFilesAndDirectoriesSegmentResponse: + """Returns a list of files and directories under the specified share or directory. It lists the + contents only for a single level of the directory hierarchy. + + :keyword prefix: Filters the results to return only items whose name begins with the specified + prefix. Default value is None. + :paramtype prefix: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of items to return. Default value is None. + :paramtype maxresults: int + :keyword include: Include this parameter to specify one or more datasets to include in the + response. Default value is None. + :paramtype include: list[str or ~azure.storage.fileshare.models.ListFilesIncludeType] + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword include_extended_info: Include extended information. Default value is None. + :paramtype include_extended_info: bool + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: ListFilesAndDirectoriesSegmentResponse. The ListFilesAndDirectoriesSegmentResponse is + compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ListFilesAndDirectoriesSegmentResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListFilesAndDirectoriesSegmentResponse] = kwargs.pop("cls", None) + + _request = build_directory_list_files_and_directories_segment_request( + prefix=prefix, + sharesnapshot=sharesnapshot, + marker=marker, + maxresults=maxresults, + include=include, + timeout=timeout, + include_extended_info=include_extended_info, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListFilesAndDirectoriesSegmentResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_handles( + self, + *, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.ListHandlesResponse: + """Lists handles for directory. + + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of items to return. Default value is None. + :paramtype maxresults: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword recursive: Specifies operation should apply to the directory specified in the URI, its + files, its subdirectories and their files. Default value is None. + :paramtype recursive: bool + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) + + _request = build_directory_list_handles_request( + marker=marker, + maxresults=maxresults, + timeout=timeout, + sharesnapshot=sharesnapshot, + recursive=recursive, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListHandlesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def force_close_handles( + self, + *, + handle_id: str, + timeout: Optional[int] = None, + marker: Optional[str] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Closes all handles open for given directory. + + :keyword handle_id: Specifies handle ID opened on the file or directory to be closed. Asterisk + ('*') is a wildcard that specifies all handles. Required. + :paramtype handle_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword recursive: Specifies operation should apply to the directory specified in the URI, its + files, its subdirectories and their files. Default value is None. + :paramtype recursive: bool + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_force_close_handles_request( + handle_id=handle_id, + timeout=timeout, + marker=marker, + sharesnapshot=sharesnapshot, + recursive=recursive, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-marker"] = self._deserialize("str", response.headers.get("x-ms-marker")) + response_headers["x-ms-number-of-handles-closed"] = self._deserialize( + "int", response.headers.get("x-ms-number-of-handles-closed") + ) + response_headers["x-ms-number-of-handles-failed"] = self._deserialize( + "int", response.headers.get("x-ms-number-of-handles-failed") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def rename( # pylint: disable=too-many-locals + self, + *, + rename_source: str, + timeout: Optional[int] = None, + replace_if_exists: Optional[bool] = None, + ignore_read_only: Optional[bool] = None, + source_lease_id: Optional[str] = None, + destination_lease_id: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Renames a directory. By default, the destination is overwritten and if the destination already + exists and has a read-only attribute set, the operation will fail. + + :keyword rename_source: Required. Specifies the URI-style path of the source file, up to 2 KB + in length. Required. + :paramtype rename_source: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword replace_if_exists: Boolean. Default value is false. Set to true to indicate that the + destination should be overwritten. Default value is None. + :paramtype replace_if_exists: bool + :keyword ignore_read_only: Boolean. Default value is false. Set to true to overwrite the + destination even if it has the read-only attribute set. Default value is None. + :paramtype ignore_read_only: bool + :keyword source_lease_id: Required if the source file has an active lease. Default value is + None. + :paramtype source_lease_id: str + :keyword destination_lease_id: Required if the destination has an active lease. Default value + is None. + :paramtype destination_lease_id: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the directory. Default value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the directory. Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the directory. Default value is None. + :paramtype file_change_time: str + :keyword file_permission: If specified the permission shall be set for the directory. Default + value is None. + :paramtype file_permission: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_permission_key: Key of the permission to be set. Default value is None. + :paramtype file_permission_key: str + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the + source URI. Default value is None. + :paramtype allow_source_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_rename_request( + rename_source=rename_source, + timeout=timeout, + replace_if_exists=replace_if_exists, + ignore_read_only=ignore_read_only, + source_lease_id=source_lease_id, + destination_lease_id=destination_lease_id, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission=file_permission, + file_permission_format=file_permission_format, + file_permission_key=file_permission_key, + metadata=metadata, + allow_trailing_dot=allow_trailing_dot, + allow_source_trailing_dot=allow_source_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + +class FileOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.aio.FileClient`'s + :attr:`file` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FileClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def create( # pylint: disable=too-many-locals + self, + optional_body: Optional[bytes] = None, + *, + file_content_length: int, + timeout: Optional[int] = None, + file_content_type: Optional[str] = None, + file_content_encoding: Optional[str] = None, + file_content_language: Optional[str] = None, + file_cache_control: Optional[str] = None, + file_content_md5: Optional[bytes] = None, + file_content_disposition: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, + content_md5: Optional[bytes] = None, + file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, + content_length: Optional[int] = None, + structured_body_type: Optional[str] = None, + structured_content_length: Optional[int] = None, + **kwargs: Any + ) -> None: + """Creates a new file or replaces a file. Note it only initializes the file with no content. + + :param optional_body: Initial data. Default value is None. + :type optional_body: bytes + :keyword file_content_length: Specifies the maximum size for the file, up to 4 TB. Required. + :paramtype file_content_length: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_content_type: Sets the MIME content type of the file. The default type is + 'application/octet-stream'. Default value is None. + :paramtype file_content_type: str + :keyword file_content_encoding: Specifies which content encodings have been applied to the + file. Default value is None. + :paramtype file_content_encoding: str + :keyword file_content_language: Specifies the natural languages used by this resource. Default + value is None. + :paramtype file_content_language: str + :keyword file_cache_control: Sets the file's cache control. The File service stores this value + but does not use or modify it. Default value is None. + :paramtype file_cache_control: str + :keyword file_content_md5: An MD5 hash of the file content. This hash is used to verify the + integrity of the file during transport. Default value is None. + :paramtype file_content_md5: bytes + :keyword file_content_disposition: Sets the file's Content-Disposition header. Default value is + None. + :paramtype file_content_disposition: str + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_permission: If specified the permission (security descriptor) shall be set for + the directory/file. This header can be used if Permission size is <= 8KB, else + x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as + input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or + x-ms-file-permission-key should be specified. Default value is None. + :paramtype file_permission: str + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default + value is None. + :paramtype file_permission_key: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value: 'Archive' for file and 'Directory' for directory. 'None' can also be specified as + default. Default value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file/directory. Default value: Now. + Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_change_time: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :keyword nfs_file_type: Optional, NFS only. Type of the file or directory. Known values are: + "Regular", "Directory", and "SymLink". Default value is None. + :paramtype nfs_file_type: str or ~azure.storage.fileshare.models.NfsFileType + :keyword content_md5: An MD5 hash of the content. This hash is used to verify the integrity of + the data during transport. Default value is None. + :paramtype content_md5: bytes + :keyword file_property_semantics: SMB only. Default value is New. Known values are: "New" and + "Restore". Default value is None. + :paramtype file_property_semantics: str or + ~azure.storage.fileshare.models.FilePropertySemantics + :keyword content_length: Specifies the number of bytes being transmitted in the request body. + When the x-ms-write header is set to clear, the value of this header must be set to zero.". + Default value is None. + :paramtype content_length: int + :keyword structured_body_type: Specifies the response content should be returned as a + structured message and specifies the message schema version and properties. Default value is + None. + :paramtype structured_body_type: str + :keyword structured_content_length: Required if the request body is a structured message. + Specifies the length of the blob/file content inside the message body. Will always be smaller + than Content-Length. Default value is None. + :paramtype structured_content_length: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + file_type: Literal["file"] = kwargs.pop("file_type", _headers.pop("x-ms-type", "file")) + content_type: Optional[str] = kwargs.pop( + "content_type", _headers.pop("Content-Type", "application/octet-stream") + ) + content_type = content_type if optional_body else None + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = optional_body + + _request = build_file_create_request( + file_content_length=file_content_length, + timeout=timeout, + file_content_type=file_content_type, + file_content_encoding=file_content_encoding, + file_content_language=file_content_language, + file_cache_control=file_cache_control, + file_content_md5=file_content_md5, + file_content_disposition=file_content_disposition, + metadata=metadata, + file_permission=file_permission, + file_permission_key=file_permission_key, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission_format=file_permission_format, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + nfs_file_type=nfs_file_type, + content_md5=content_md5, + file_property_semantics=file_property_semantics, + content_length=content_length, + structured_body_type=structured_body_type, + structured_content_length=structured_content_length, + file_type=file_type, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) + response_headers["x-ms-structured-body"] = self._deserialize( + "str", response.headers.get("x-ms-structured-body") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def download( + self, + *, + timeout: Optional[int] = None, + range: Optional[str] = None, + range_get_content_md5: Optional[bool] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + structured_body_type: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterator[bytes]: + """Reads or downloads a file from the system, including its metadata and properties. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword range: Return file data only from the specified byte range. Default value is None. + :paramtype range: str + :keyword range_get_content_md5: When this header is set to true and specified together with the + Range header, the service returns the MD5 hash for the range, as long as the range is less than + or equal to 4 MB in size. Default value is None. + :paramtype range_get_content_md5: bool + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword structured_body_type: Specifies the response content should be returned as a + structured message and specifies the message schema version and properties. Default value is + None. + :paramtype structured_body_type: str + :return: AsyncIterator[bytes] + :rtype: AsyncIterator[bytes] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_file_download_request( + timeout=timeout, + range=range, + range_get_content_md5=range_get_content_md5, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + structured_body_type=structured_body_type, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", True) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) + response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) + response_headers["Content-Range"] = self._deserialize("str", response.headers.get("Content-Range")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["Content-Encoding"] = self._deserialize("str", response.headers.get("Content-Encoding")) + response_headers["Cache-Control"] = self._deserialize("str", response.headers.get("Cache-Control")) + response_headers["Content-Disposition"] = self._deserialize("str", response.headers.get("Content-Disposition")) + response_headers["Content-Language"] = self._deserialize("str", response.headers.get("Content-Language")) + response_headers["Accept-Ranges"] = self._deserialize("str", response.headers.get("Accept-Ranges")) + response_headers["x-ms-copy-completion-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-copy-completion-time") + ) + response_headers["x-ms-copy-status-description"] = self._deserialize( + "str", response.headers.get("x-ms-copy-status-description") + ) + response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) + response_headers["x-ms-copy-progress"] = self._deserialize("str", response.headers.get("x-ms-copy-progress")) + response_headers["x-ms-copy-source"] = self._deserialize("str", response.headers.get("x-ms-copy-source")) + response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) + response_headers["x-ms-content-md5"] = self._deserialize("bytearray", response.headers.get("x-ms-content-md5")) + response_headers["x-ms-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) + response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) + response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) + response_headers["x-ms-structured-body"] = self._deserialize( + "str", response.headers.get("x-ms-structured-body") + ) + response_headers["x-ms-structured-content-length"] = self._deserialize( + "int", response.headers.get("x-ms-structured-content-length") + ) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_properties( + self, + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> bool: + """Returns all user-defined metadata, standard HTTP properties, and system properties for the + file. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: bool + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_get_properties_request( + sharesnapshot=sharesnapshot, + timeout=timeout, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) + response_headers["x-ms-type"] = self._deserialize("str", response.headers.get("x-ms-type")) + response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["Content-Encoding"] = self._deserialize("str", response.headers.get("Content-Encoding")) + response_headers["Cache-Control"] = self._deserialize("str", response.headers.get("Cache-Control")) + response_headers["Content-Disposition"] = self._deserialize("str", response.headers.get("Content-Disposition")) + response_headers["Content-Language"] = self._deserialize("str", response.headers.get("Content-Language")) + response_headers["x-ms-copy-completion-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-copy-completion-time") + ) + response_headers["x-ms-copy-status-description"] = self._deserialize( + "str", response.headers.get("x-ms-copy-status-description") + ) + response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) + response_headers["x-ms-copy-progress"] = self._deserialize("str", response.headers.get("x-ms-copy-progress")) + response_headers["x-ms-copy-source"] = self._deserialize("str", response.headers.get("x-ms-copy-source")) + response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) + response_headers["x-ms-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) + response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) + response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 + + @distributed_trace_async + async def delete( + self, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Removes the file from the storage account. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_delete_request( + timeout=timeout, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def set_http_headers( # pylint: disable=too-many-locals + self, + *, + timeout: Optional[int] = None, + file_content_length: Optional[int] = None, + file_content_type: Optional[str] = None, + file_content_encoding: Optional[str] = None, + file_content_language: Optional[str] = None, + file_cache_control: Optional[str] = None, + file_content_md5: Optional[bytes] = None, + file_content_disposition: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + **kwargs: Any + ) -> None: + """Sets HTTP headers on a file. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_content_length: Specifies the number of bytes being transmitted. Default value is + None. + :paramtype file_content_length: int + :keyword file_content_type: Sets the MIME content type of the file. The default type is + 'application/octet-stream'. Default value is None. + :paramtype file_content_type: str + :keyword file_content_encoding: Specifies which content encodings have been applied to the + file. Default value is None. + :paramtype file_content_encoding: str + :keyword file_content_language: Specifies the natural languages used by this resource. Default + value is None. + :paramtype file_content_language: str + :keyword file_cache_control: Sets the file's cache control. The File service stores this value + but does not use or modify it. Default value is None. + :paramtype file_cache_control: str + :keyword file_content_md5: An MD5 hash of the file content. This hash is used to verify the + integrity of the file during transport. Default value is None. + :paramtype file_content_md5: bytes + :keyword file_content_disposition: Sets the file's Content-Disposition header. Default value is + None. + :paramtype file_content_disposition: str + :keyword file_permission: If specified the permission (security descriptor) shall be set for + the directory/file. This header can be used if Permission size is <= 8KB, else + x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as + input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or + x-ms-file-permission-key should be specified. Default value is None. + :paramtype file_permission: str + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default + value is None. + :paramtype file_permission_key: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value: 'Archive' for file and 'Directory' for directory. 'None' can also be specified as + default. Default value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file/directory. Default value: Now. + Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_change_time: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_set_http_headers_request( + timeout=timeout, + file_content_length=file_content_length, + file_content_type=file_content_type, + file_content_encoding=file_content_encoding, + file_content_language=file_content_language, + file_cache_control=file_cache_control, + file_content_md5=file_content_md5, + file_content_disposition=file_content_disposition, + file_permission=file_permission, + file_permission_key=file_permission_key, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission_format=file_permission_format, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def set_metadata( + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Sets one or more user-defined name-value pairs for the specified file. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_set_metadata_request( + timeout=timeout, + metadata=metadata, + lease_id=lease_id, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def acquire_lease( + self, + *, + timeout: Optional[int] = None, + lease_duration: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_duration: Specifies the duration of the lease, in seconds, or negative one (-1) + for a lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease + duration cannot be changed using renew or change. Default value is None. + :paramtype lease_duration: int + :keyword proposed_lease_id: Proposed lease ID, in a GUID string format. The File service + returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid + Constructor (String) for a list of valid GUID string formats. Default value is None. + :paramtype proposed_lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_acquire_lease_request( + timeout=timeout, + lease_duration=lease_duration, + proposed_lease_id=proposed_lease_id, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def release_lease( + self, + *, + lease_id: str, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_release_lease_request( + lease_id=lease_id, + timeout=timeout, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def change_lease( + self, + *, + lease_id: str, + timeout: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword proposed_lease_id: Proposed lease ID, in a GUID string format. The File service + returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid + Constructor (String) for a list of valid GUID string formats. Default value is None. + :paramtype proposed_lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_change_lease_request( + lease_id=lease_id, + timeout=timeout, + proposed_lease_id=proposed_lease_id, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def break_lease( + self, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_break_lease_request( + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-time"] = self._deserialize("int", response.headers.get("x-ms-lease-time")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def upload_range( # pylint: disable=too-many-locals + self, + optional_body: Optional[bytes] = None, + *, + range: str, + file_range_write: Union[str, _models.FileRangeWriteType], + content_length: int, + timeout: Optional[int] = None, + content_md5: Optional[bytes] = None, + lease_id: Optional[str] = None, + file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + structured_body_type: Optional[str] = None, + structured_content_length: Optional[int] = None, + **kwargs: Any + ) -> None: + """Upload a range of bytes to a file. + + :param optional_body: Initial data. Default value is None. + :type optional_body: bytes + :keyword range: Specifies the range of bytes to be written. Both the start and end of the range + must be specified. Required. + :paramtype range: str + :keyword file_range_write: Specify one of the following options: - Update: Writes the bytes + specified by the request body into the specified range. - Clear: Clears the specified range and + releases the space used in storage for that range. Known values are: "update" and "clear". + Required. + :paramtype file_range_write: str or ~azure.storage.fileshare.models.FileRangeWriteType + :keyword content_length: The number of bytes being transmitted in the request body. Required. + :paramtype content_length: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword content_md5: An MD5 hash of the content. This hash is used to verify the integrity of + the data during transport. Default value is None. + :paramtype content_md5: bytes + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_last_written_mode: If the file last write time should be preserved or + overwritten. Known values are: "Now" and "Preserve". Default value is None. + :paramtype file_last_written_mode: str or ~azure.storage.fileshare.models.FileLastWrittenMode + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword structured_body_type: Specifies the response content should be returned as a + structured message and specifies the message schema version and properties. Default value is + None. + :paramtype structured_body_type: str + :keyword structured_content_length: Required if the request body is a structured message. + Specifies the length of the blob/file content inside the message body. Will always be smaller + than Content-Length. Default value is None. + :paramtype structured_content_length: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop( + "content_type", _headers.pop("Content-Type", "application/octet-stream") + ) + content_type = content_type if optional_body else None + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = optional_body + + _request = build_file_upload_range_request( + range=range, + file_range_write=file_range_write, + content_length=content_length, + timeout=timeout, + content_md5=content_md5, + lease_id=lease_id, + file_last_written_mode=file_last_written_mode, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + structured_body_type=structured_body_type, + structured_content_length=structured_content_length, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-structured-body"] = self._deserialize( + "str", response.headers.get("x-ms-structured-body") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def upload_range_from_url( # pylint: disable=too-many-locals + self, + *, + range: str, + copy_source: str, + file_range_write_from_url: Union[str, _models.FileRangeWriteFromUrlType], + content_length: int, + source_range: Optional[str] = None, + timeout: Optional[int] = None, + source_content_crc64: Optional[bytes] = None, + source_if_match_crc64: Optional[bytes] = None, + source_if_none_match_crc64: Optional[bytes] = None, + lease_id: Optional[str] = None, + copy_source_authorization: Optional[str] = None, + file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Upload a range of bytes to a file where the contents are read from a URL. + + :keyword range: Specifies the range of bytes to be written. Both the start and end of the range + must be specified. Required. + :paramtype range: str + :keyword copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. + Required. + :paramtype copy_source: str + :keyword file_range_write_from_url: Only update is supported. "update" Required. + :paramtype file_range_write_from_url: str or + ~azure.storage.fileshare.models.FileRangeWriteFromUrlType + :keyword content_length: The number of bytes being transmitted in the request body. Required. + :paramtype content_length: int + :keyword source_range: Bytes of source data in the specified range. Default value is None. + :paramtype source_range: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword source_content_crc64: Specify the CRC64 hash of the source content. Default value is + None. + :paramtype source_content_crc64: bytes + :keyword source_if_match_crc64: Specify the CRC64 hash value to check for source content + integrity. Default value is None. + :paramtype source_if_match_crc64: bytes + :keyword source_if_none_match_crc64: Specify the CRC64 hash value to check for source content + mismatch. Default value is None. + :paramtype source_if_none_match_crc64: bytes + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword copy_source_authorization: Only Bearer type is supported. Credentials should be a + valid OAuth access token to copy source. Default value is None. + :paramtype copy_source_authorization: str + :keyword file_last_written_mode: If the file last write time should be preserved or + overwritten. Known values are: "Now" and "Preserve". Default value is None. + :paramtype file_last_written_mode: str or ~azure.storage.fileshare.models.FileLastWrittenMode + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the + source URI. Default value is None. + :paramtype allow_source_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_upload_range_from_url_request( + range=range, + copy_source=copy_source, + file_range_write_from_url=file_range_write_from_url, + content_length=content_length, + source_range=source_range, + timeout=timeout, + source_content_crc64=source_content_crc64, + source_if_match_crc64=source_if_match_crc64, + source_if_none_match_crc64=source_if_none_match_crc64, + lease_id=lease_id, + copy_source_authorization=copy_source_authorization, + file_last_written_mode=file_last_written_mode, + allow_trailing_dot=allow_trailing_dot, + allow_source_trailing_dot=allow_source_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["x-ms-content-crc64"] = self._deserialize( + "bytearray", response.headers.get("x-ms-content-crc64") + ) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_range_list( + self, + *, + sharesnapshot: Optional[str] = None, + prevsharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + range: Optional[str] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + support_rename: Optional[bool] = None, + **kwargs: Any + ) -> _models.ShareFileRangeList: + """Returns the list of valid page ranges for a file or snapshot of a file. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword prevsharesnapshot: The previous snapshot parameter is an opaque DateTime value that + specifies a previous file snapshot to compare against. Default value is None. + :paramtype prevsharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword range: Return file data only from the specified byte range. Default value is None. + :paramtype range: str + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword support_rename: This header is allowed only when PrevShareSnapshot query parameter is + set. Determines whether the changed ranges for a file that has been renamed or moved should be + listed. Default value is None. + :paramtype support_rename: bool + :return: ShareFileRangeList. The ShareFileRangeList is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ShareFileRangeList + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ShareFileRangeList] = kwargs.pop("cls", None) + + _request = build_file_get_range_list_request( + sharesnapshot=sharesnapshot, + prevsharesnapshot=prevsharesnapshot, + timeout=timeout, + range=range, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + support_rename=support_rename, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["x-ms-content-length"] = self._deserialize("int", response.headers.get("x-ms-content-length")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ShareFileRangeList, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def start_copy( # pylint: disable=too-many-locals + self, + *, + copy_source: str, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + file_permission_copy_mode: Optional[Union[str, _models.PermissionCopyModeType]] = None, + ignore_read_only: Optional[bool] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + set_archive_attribute: Optional[bool] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + file_mode_copy_mode: Optional[Union[str, _models.ModeCopyMode]] = None, + file_owner_copy_mode: Optional[Union[str, _models.OwnerCopyMode]] = None, + **kwargs: Any + ) -> None: + """Copies a blob or file to a destination file within the storage account. + + :keyword copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. + Required. + :paramtype copy_source: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_permission: If specified the permission shall be set for the file. Default value + is None. + :paramtype file_permission: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_permission_key: Key of the permission to be set. Default value is None. + :paramtype file_permission_key: str + :keyword file_permission_copy_mode: Specifies the option to copy file security descriptor from + source file or to set it using the value which is defined by the header value of + x-ms-file-permission or x-ms-file-permission-key. Known values are: "source" and "override". + Default value is None. + :paramtype file_permission_copy_mode: str or + ~azure.storage.fileshare.models.PermissionCopyModeType + :keyword ignore_read_only: A boolean value that specifies whether the ReadOnly attribute on a + preexisting destination file should be respected or overridden. Default value is None. + :paramtype ignore_read_only: bool + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file. Default value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file. Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file. Default value is None. + :paramtype file_change_time: str + :keyword set_archive_attribute: Optional. Sets the archive attribute on the destination file. + Default value is None. + :paramtype set_archive_attribute: bool + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the + source URI. Default value is None. + :paramtype allow_source_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :keyword file_mode_copy_mode: Specifies mode copy option for the file. Known values are: + "source" and "override". Default value is None. + :paramtype file_mode_copy_mode: str or ~azure.storage.fileshare.models.ModeCopyMode + :keyword file_owner_copy_mode: Specifies owner copy option for the file. Known values are: + "source" and "override". Default value is None. + :paramtype file_owner_copy_mode: str or ~azure.storage.fileshare.models.OwnerCopyMode + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_start_copy_request( + copy_source=copy_source, + timeout=timeout, + metadata=metadata, + file_permission=file_permission, + file_permission_format=file_permission_format, + file_permission_key=file_permission_key, + file_permission_copy_mode=file_permission_copy_mode, + ignore_read_only=ignore_read_only, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + set_archive_attribute=set_archive_attribute, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + allow_source_trailing_dot=allow_source_trailing_dot, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + file_mode_copy_mode=file_mode_copy_mode, + file_owner_copy_mode=file_owner_copy_mode, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) + response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def abort_copy( + self, + *, + copyid: str, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Aborts a pending Copy File operation, and leaves a destination file with zero length and full + metadata. + + :keyword copyid: The copy identifier provided in the x-ms-copy-id header of the original Copy + File operation. Required. + :paramtype copyid: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + copy_action_abort_constant: Literal["abort"] = kwargs.pop( + "copy_action_abort_constant", _headers.pop("x-ms-copy-action", "abort") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_abort_copy_request( + copyid=copyid, + timeout=timeout, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + copy_action_abort_constant=copy_action_abort_constant, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def list_handles( + self, + *, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.ListHandlesResponse: + """Lists handles for file. + + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of items to return. Default value is None. + :paramtype maxresults: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) + + _request = build_file_list_handles_request( + marker=marker, + maxresults=maxresults, + timeout=timeout, + sharesnapshot=sharesnapshot, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListHandlesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def force_close_handles( + self, + *, + handle_id: str, + timeout: Optional[int] = None, + marker: Optional[str] = None, + sharesnapshot: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Closes all handles open for given file. + + :keyword handle_id: Specifies handle ID opened on the file or directory to be closed. Asterisk + ('*') is a wildcard that specifies all handles. Required. + :paramtype handle_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_force_close_handles_request( + handle_id=handle_id, + timeout=timeout, + marker=marker, + sharesnapshot=sharesnapshot, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-marker"] = self._deserialize("str", response.headers.get("x-ms-marker")) + response_headers["x-ms-number-of-handles-closed"] = self._deserialize( + "int", response.headers.get("x-ms-number-of-handles-closed") + ) + response_headers["x-ms-number-of-handles-failed"] = self._deserialize( + "int", response.headers.get("x-ms-number-of-handles-failed") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def rename( # pylint: disable=too-many-locals + self, + *, + rename_source: str, + timeout: Optional[int] = None, + replace_if_exists: Optional[bool] = None, + ignore_read_only: Optional[bool] = None, + source_lease_id: Optional[str] = None, + destination_lease_id: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + file_content_type: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Renames a file. By default, the destination is overwritten and if the destination already + exists and has a read-only attribute set, the operation will fail. + + :keyword rename_source: Required. Specifies the URI-style path of the source file, up to 2 KB + in length. Required. + :paramtype rename_source: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword replace_if_exists: Boolean. Default value is false. Set to true to indicate that the + destination should be overwritten. Default value is None. + :paramtype replace_if_exists: bool + :keyword ignore_read_only: Boolean. Default value is false. Set to true to overwrite the + destination even if it has the read-only attribute set. Default value is None. + :paramtype ignore_read_only: bool + :keyword source_lease_id: Required if the source file has an active lease. Default value is + None. + :paramtype source_lease_id: str + :keyword destination_lease_id: Required if the destination has an active lease. Default value + is None. + :paramtype destination_lease_id: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file. Default value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file. Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file. Default value is None. + :paramtype file_change_time: str + :keyword file_permission: If specified the permission shall be set for the file. Default value + is None. + :paramtype file_permission: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_permission_key: Key of the permission to be set. Default value is None. + :paramtype file_permission_key: str + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_content_type: Sets the MIME content type of the file. Default value is None. + :paramtype file_content_type: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the + source URI. Default value is None. + :paramtype allow_source_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_rename_request( + rename_source=rename_source, + timeout=timeout, + replace_if_exists=replace_if_exists, + ignore_read_only=ignore_read_only, + source_lease_id=source_lease_id, + destination_lease_id=destination_lease_id, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission=file_permission, + file_permission_format=file_permission_format, + file_permission_key=file_permission_key, + metadata=metadata, + file_content_type=file_content_type, + allow_trailing_dot=allow_trailing_dot, + allow_source_trailing_dot=allow_source_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def create_symbolic_link( + self, + *, + link_text: str, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + lease_id: Optional[str] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Creates a symbolic link to a target file. NFS only. + + :keyword link_text: NFS only. The path to the original file, the symbolic link is pointing to. + Required. + :paramtype link_text: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_creation_time: Creation time for the file. Default value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file. Default value is None. + :paramtype file_last_write_time: str + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_create_symbolic_link_request( + link_text=link_text, + timeout=timeout, + metadata=metadata, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + lease_id=lease_id, + owner=owner, + group=group, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_symbolic_link( + self, + *, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Returns the target of a symbolic link. NFS only. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_get_symbolic_link_request( + timeout=timeout, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-link-text"] = self._deserialize("str", response.headers.get("x-ms-link-text")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def create_hard_link( + self, + *, + target_file: str, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Creates a hard link to a target file. NFS only. + + :keyword target_file: NFS only. Required. Specifies the path of the target file to which the + link will be created, up to 2 KiB in length. Required. + :paramtype target_file: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + file_type: Literal["file"] = kwargs.pop("file_type", _headers.pop("x-ms-type", "file")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_create_hard_link_request( + target_file=target_file, + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + file_type=file_type, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.aio.FileClient`'s + :attr:`service` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FileClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def set_properties( + self, + storage_service_properties: _models.StorageServiceProperties, + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Sets properties for a storage account's File service endpoint, including properties for Storage + Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. + + :param storage_service_properties: Storage service properties. Required. + :type storage_service_properties: + ~azure.storage.fileshare._generated.models.StorageServiceProperties + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = _get_element(storage_service_properties) + + _request = build_service_set_properties_request( + timeout=timeout, + file_request_intent=file_request_intent, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_properties( + self, + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.StorageServiceProperties: + """Gets the properties of a storage account's File service, including properties for Storage + Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: StorageServiceProperties. The StorageServiceProperties is compatible with + MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.StorageServiceProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.StorageServiceProperties] = kwargs.pop("cls", None) + + _request = build_service_get_properties_request( + timeout=timeout, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.StorageServiceProperties, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def list_shares_segment( + self, + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + include: Optional[list[Union[str, _models.ListSharesIncludeType]]] = None, + **kwargs: Any + ) -> _models.ListSharesResponse: + """The List Shares Segment operation returns a list of the shares and share snapshots under the + specified account. + + :keyword prefix: Filters the results to return only items whose name begins with the specified + prefix. Default value is None. + :paramtype prefix: str + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of items to return. Default value is None. + :paramtype maxresults: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword include: Include this parameter to specify one or more datasets to include in the + response. Default value is None. + :paramtype include: list[str or ~azure.storage.fileshare.models.ListSharesIncludeType] + :return: ListSharesResponse. The ListSharesResponse is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ListSharesResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListSharesResponse] = kwargs.pop("cls", None) + + _request = build_service_list_shares_segment_request( + prefix=prefix, + marker=marker, + maxresults=maxresults, + timeout=timeout, + file_request_intent=file_request_intent, + include=include, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListSharesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_user_delegation_key( + self, key_info: _models.KeyInfo, *, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.UserDelegationKey: + """Retrieves a user delegation key for the File service. This can be used to generate a user + delegation SAS. + + :param key_info: Key information. Required. + :type key_info: ~azure.storage.fileshare._generated.models.KeyInfo + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :return: UserDelegationKey. The UserDelegationKey is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.UserDelegationKey + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) + + _content = _get_element(key_info) + + _request = build_service_get_user_delegation_key_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.UserDelegationKey, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + +class ShareOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.aio.FileClient`'s + :attr:`share` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FileClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace_async + async def create( # pylint: disable=too-many-locals + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + quota: Optional[int] = None, + access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, + enabled_protocols: Optional[str] = None, + root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, + enable_snapshot_virtual_directory_access: Optional[bool] = None, + paid_bursting_enabled: Optional[bool] = None, + paid_bursting_max_iops: Optional[int] = None, + paid_bursting_max_bandwidth_mibps: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + share_provisioned_iops: Optional[int] = None, + share_provisioned_bandwidth_mibps: Optional[int] = None, + enable_smb_directory_lease: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Creates a new share under the specified account. If the share with the same name already + exists, the operation fails. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword quota: Specifies the maximum size of the share, in gigabytes. Default value is None. + :paramtype quota: int + :keyword access_tier: Specifies the access tier of the share. Known values are: + "TransactionOptimized", "Hot", "Cool", and "Premium". Default value is None. + :paramtype access_tier: str or ~azure.storage.fileshare.models.ShareAccessTier + :keyword enabled_protocols: Protocols to enable on the share. Default value is None. + :paramtype enabled_protocols: str + :keyword root_squash: Root squash to set on the share. Only valid for NFS shares. Known values + are: "NoRootSquash", "RootSquash", and "AllSquash". Default value is None. + :paramtype root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash + :keyword enable_snapshot_virtual_directory_access: Optional. Used to enable snapshot virtual + directory access. Default value is None. + :paramtype enable_snapshot_virtual_directory_access: bool + :keyword paid_bursting_enabled: Optional. Boolean. Default if not specified is false. This + property enables paid bursting. Default value is None. + :paramtype paid_bursting_enabled: bool + :keyword paid_bursting_max_iops: Optional. Integer. Default if not specified is the maximum + IOPS the file share can support. Current maximum for a file share is 102,400 IOPS. Default + value is None. + :paramtype paid_bursting_max_iops: int + :keyword paid_bursting_max_bandwidth_mibps: Optional. Integer. Default if not specified is the + maximum throughput the file share can support. Current maximum for a file share is 10,340 + MiB/sec. Default value is None. + :paramtype paid_bursting_max_bandwidth_mibps: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword share_provisioned_iops: Optional. Specifies the provisioned IOPS of the share. Default + value is None. + :paramtype share_provisioned_iops: int + :keyword share_provisioned_bandwidth_mibps: Optional. Specifies the provisioned bandwidth of + the share, in MiBps. Default value is None. + :paramtype share_provisioned_bandwidth_mibps: int + :keyword enable_smb_directory_lease: Optional. Used to enable SMB directory lease. Default + value is None. + :paramtype enable_smb_directory_lease: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_create_request( + timeout=timeout, + metadata=metadata, + quota=quota, + access_tier=access_tier, + enabled_protocols=enabled_protocols, + root_squash=root_squash, + enable_snapshot_virtual_directory_access=enable_snapshot_virtual_directory_access, + paid_bursting_enabled=paid_bursting_enabled, + paid_bursting_max_iops=paid_bursting_max_iops, + paid_bursting_max_bandwidth_mibps=paid_bursting_max_bandwidth_mibps, + file_request_intent=file_request_intent, + share_provisioned_iops=share_provisioned_iops, + share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, + enable_smb_directory_lease=enable_smb_directory_lease, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) + response_headers["x-ms-share-provisioned-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-iops") + ) + response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") + ) + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") + ) + response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_properties( + self, + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + lease_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """Returns all user-defined metadata and system properties for the specified share or share + snapshot. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_get_properties_request( + sharesnapshot=sharesnapshot, + timeout=timeout, + file_request_intent=file_request_intent, + lease_id=lease_id, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) + response_headers["x-ms-share-provisioned-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-iops") + ) + response_headers["x-ms-share-provisioned-ingress-mbps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-ingress-mbps") + ) + response_headers["x-ms-share-provisioned-egress-mbps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-egress-mbps") + ) + response_headers["x-ms-share-next-allowed-quota-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-quota-downgrade-time") + ) + response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") + ) + response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) + response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) + response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) + response_headers["x-ms-access-tier"] = self._deserialize("str", response.headers.get("x-ms-access-tier")) + response_headers["x-ms-access-tier-change-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-access-tier-change-time") + ) + response_headers["x-ms-access-tier-transition-state"] = self._deserialize( + "str", response.headers.get("x-ms-access-tier-transition-state") + ) + response_headers["x-ms-enabled-protocols"] = self._deserialize( + "str", response.headers.get("x-ms-enabled-protocols") + ) + response_headers["x-ms-root-squash"] = self._deserialize("str", response.headers.get("x-ms-root-squash")) + response_headers["x-ms-enable-snapshot-virtual-directory-access"] = self._deserialize( + "bool", response.headers.get("x-ms-enable-snapshot-virtual-directory-access") + ) + response_headers["x-ms-share-paid-bursting-enabled"] = self._deserialize( + "bool", response.headers.get("x-ms-share-paid-bursting-enabled") + ) + response_headers["x-ms-share-paid-bursting-max-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-paid-bursting-max-iops") + ) + response_headers["x-ms-share-paid-bursting-max-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-paid-bursting-max-bandwidth-mibps") + ) + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") + ) + response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + ) + response_headers["x-ms-share-next-allowed-provisioned-iops-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-iops-downgrade-time") + ) + response_headers["x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time") + ) + response_headers["x-ms-enable-smb-directory-lease"] = self._deserialize( + "bool", response.headers.get("x-ms-enable-smb-directory-lease") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def delete( + self, + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + lease_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """Operation marks the specified share or share snapshot for deletion. The share or share snapshot + and any files contained within it are later deleted during garbage collection. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword delete_snapshots: Specifies the option include to delete the base share and all of its + snapshots. Known values are: "include" and "include-leased". Default value is None. + :paramtype delete_snapshots: str or ~azure.storage.fileshare.models.DeleteSnapshotsOptionType + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_delete_request( + sharesnapshot=sharesnapshot, + timeout=timeout, + delete_snapshots=delete_snapshots, + file_request_intent=file_request_intent, + lease_id=lease_id, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-file-share-usage-bytes"] = self._deserialize( + "int", response.headers.get("x-ms-file-share-usage-bytes") + ) + response_headers["x-ms-file-share-snapshot-usage-bytes"] = self._deserialize( + "int", response.headers.get("x-ms-file-share-snapshot-usage-bytes") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def acquire_lease( + self, + *, + timeout: Optional[int] = None, + lease_duration: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_duration: Specifies the duration of the lease, in seconds, or negative one (-1) + for a lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease + duration cannot be changed using renew or change. Default value is None. + :paramtype lease_duration: int + :keyword proposed_lease_id: Proposed lease ID, in a GUID string format. The File service + returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid + Constructor (String) for a list of valid GUID string formats. Default value is None. + :paramtype proposed_lease_id: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_acquire_lease_request( + timeout=timeout, + lease_duration=lease_duration, + proposed_lease_id=proposed_lease_id, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def release_lease( + self, + *, + lease_id: str, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_release_lease_request( + lease_id=lease_id, + timeout=timeout, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def change_lease( + self, + *, + lease_id: str, + proposed_lease_id: Optional[str] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword proposed_lease_id: Proposed lease ID, in a GUID string format. The File service + returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid + Constructor (String) for a list of valid GUID string formats. Default value is None. + :paramtype proposed_lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_change_lease_request( + lease_id=lease_id, + proposed_lease_id=proposed_lease_id, + timeout=timeout, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def renew_lease( + self, + *, + lease_id: str, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["renew"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "renew")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_renew_lease_request( + lease_id=lease_id, + timeout=timeout, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def break_lease( + self, + *, + timeout: Optional[int] = None, + break_period: Optional[int] = None, + lease_id: Optional[str] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword break_period: For a break operation, proposed duration the lease should continue + before it is broken, in seconds, between 0 and 60. This break period is only used if it is + shorter than the time remaining on the lease. If longer, the time remaining on the lease is + used. A new lease will not be available before the break period has expired, but the lease may + be held for longer than the break period. If this header does not appear with a break + operation, a fixed-duration lease breaks after the remaining lease period elapses, and an + infinite lease breaks immediately. Default value is None. + :paramtype break_period: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_break_lease_request( + timeout=timeout, + break_period=break_period, + lease_id=lease_id, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-time"] = self._deserialize("int", response.headers.get("x-ms-lease-time")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def create_snapshot( + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Creates a read-only snapshot of a share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_create_snapshot_request( + timeout=timeout, + metadata=metadata, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-snapshot"] = self._deserialize("str", response.headers.get("x-ms-snapshot")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @overload + async def create_permission( + self, + permission: _models.SharePermission, + *, + content_type: str = "application/json", + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. + + :param permission: A permission (a security descriptor) at the share level. Required. + :type permission: ~azure.storage.fileshare._generated.models.SharePermission + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_permission( + self, + permission: JSON, + *, + content_type: str = "application/json", + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. + + :param permission: A permission (a security descriptor) at the share level. Required. + :type permission: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_permission( + self, + permission: IO[bytes], + *, + content_type: str = "application/json", + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. + + :param permission: A permission (a security descriptor) at the share level. Required. + :type permission: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_permission( + self, + permission: Union[_models.SharePermission, JSON, IO[bytes]], + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. + + :param permission: A permission (a security descriptor) at the share level. Is one of the + following types: SharePermission, JSON, IO[bytes] Required. + :type permission: ~azure.storage.fileshare._generated.models.SharePermission or JSON or + IO[bytes] + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(permission, (IOBase, bytes)): + _content = permission + else: + _content = json.dumps(permission, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_share_create_permission_request( + timeout=timeout, + file_request_intent=file_request_intent, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_permission( + self, + *, + file_permission_key: str, + timeout: Optional[int] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.SharePermission: + """Returns the permission (security descriptor) for a given permission key. This is used to + support file level ACLs for SMB shares. + + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Required. + :paramtype file_permission_key: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_permission_format: Optional. Specifies the format in which the permission is + returned. Acceptable values are SDDL or binary. Known values are: "Sddl" and "Binary". Default + value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: SharePermission. The SharePermission is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.SharePermission + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SharePermission] = kwargs.pop("cls", None) + + _request = build_share_get_permission_request( + file_permission_key=file_permission_key, + timeout=timeout, + file_permission_format=file_permission_format, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SharePermission, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def set_properties( # pylint: disable=too-many-locals + self, + *, + timeout: Optional[int] = None, + quota: Optional[int] = None, + access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, + lease_id: Optional[str] = None, + root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, + enable_snapshot_virtual_directory_access: Optional[bool] = None, + paid_bursting_enabled: Optional[bool] = None, + paid_bursting_max_iops: Optional[int] = None, + paid_bursting_max_bandwidth_mibps: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + share_provisioned_iops: Optional[int] = None, + share_provisioned_bandwidth_mibps: Optional[int] = None, + enable_smb_directory_lease: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Sets properties for the specified share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword quota: Specifies the maximum size of the share, in gigabytes. Default value is None. + :paramtype quota: int + :keyword access_tier: Specifies the access tier of the share. Known values are: + "TransactionOptimized", "Hot", "Cool", and "Premium". Default value is None. + :paramtype access_tier: str or ~azure.storage.fileshare.models.ShareAccessTier + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword root_squash: Root squash to set on the share. Only valid for NFS shares. Known values + are: "NoRootSquash", "RootSquash", and "AllSquash". Default value is None. + :paramtype root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash + :keyword enable_snapshot_virtual_directory_access: Optional. Used to enable snapshot virtual + directory access. Default value is None. + :paramtype enable_snapshot_virtual_directory_access: bool + :keyword paid_bursting_enabled: Optional. Boolean. Default if not specified is false. This + property enables paid bursting. Default value is None. + :paramtype paid_bursting_enabled: bool + :keyword paid_bursting_max_iops: Optional. Integer. Default if not specified is the maximum + IOPS the file share can support. Current maximum for a file share is 102,400 IOPS. Default + value is None. + :paramtype paid_bursting_max_iops: int + :keyword paid_bursting_max_bandwidth_mibps: Optional. Integer. Default if not specified is the + maximum throughput the file share can support. Current maximum for a file share is 10,340 + MiB/sec. Default value is None. + :paramtype paid_bursting_max_bandwidth_mibps: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword share_provisioned_iops: Optional. Specifies the provisioned IOPS of the share. Default + value is None. + :paramtype share_provisioned_iops: int + :keyword share_provisioned_bandwidth_mibps: Optional. Specifies the provisioned bandwidth of + the share, in MiBps. Default value is None. + :paramtype share_provisioned_bandwidth_mibps: int + :keyword enable_smb_directory_lease: Optional. Used to enable SMB directory lease. Default + value is None. + :paramtype enable_smb_directory_lease: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_set_properties_request( + timeout=timeout, + quota=quota, + access_tier=access_tier, + lease_id=lease_id, + root_squash=root_squash, + enable_snapshot_virtual_directory_access=enable_snapshot_virtual_directory_access, + paid_bursting_enabled=paid_bursting_enabled, + paid_bursting_max_iops=paid_bursting_max_iops, + paid_bursting_max_bandwidth_mibps=paid_bursting_max_bandwidth_mibps, + file_request_intent=file_request_intent, + share_provisioned_iops=share_provisioned_iops, + share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, + enable_smb_directory_lease=enable_smb_directory_lease, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) + response_headers["x-ms-share-provisioned-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-iops") + ) + response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") + ) + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") + ) + response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + ) + response_headers["x-ms-share-next-allowed-quota-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-quota-downgrade-time") + ) + response_headers["x-ms-share-next-allowed-provisioned-iops-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-iops-downgrade-time") + ) + response_headers["x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def set_metadata( + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Sets one or more user-defined name-value pairs for the specified share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_set_metadata_request( + timeout=timeout, + metadata=metadata, + lease_id=lease_id, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_access_policy( + self, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.SignedIdentifiers: + """Returns information about stored access policies specified on the share that may be used with + Shared Access Signatures. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.SignedIdentifiers + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) + + _request = build_share_get_access_policy_request( + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.SignedIdentifiers, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def set_access_policy( + self, + share_acl: Optional[_models.SignedIdentifiers] = None, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Sets stored access policies for the share that may be used with Shared Access Signatures. + + :param share_acl: The ACL for the share. Default value is None. + :type share_acl: ~azure.storage.fileshare._generated.models.SignedIdentifiers + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if share_acl else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if share_acl is not None: + _content = _get_element(share_acl) + else: + _content = None + + _request = build_share_set_access_policy_request( + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace_async + async def get_statistics( + self, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.ShareStats: + """Retrieves statistics related to the share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: ShareStats. The ShareStats is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ShareStats + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ShareStats] = kwargs.pop("cls", None) + + _request = build_share_get_statistics_request( + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ShareStats, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def restore( + self, + *, + timeout: Optional[int] = None, + deleted_share_name: Optional[str] = None, + deleted_share_version: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Restores a previously deleted share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword deleted_share_name: Specifies the name of the previously-deleted share. Default value + is None. + :paramtype deleted_share_name: str + :keyword deleted_share_version: Specifies the version of the previously-deleted share. Default + value is None. + :paramtype deleted_share_version: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_restore_request( + timeout=timeout, + deleted_share_name=deleted_share_name, + deleted_share_version=deleted_share_version, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) + response_headers["x-ms-share-provisioned-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-iops") + ) + response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") + ) + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") + ) + response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_patch.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_patch.py index f7dd32510333..87676c65a8f0 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_patch.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_patch.py @@ -1,14 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_service_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_service_operations.py deleted file mode 100644 index 4d7dafcf5895..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_service_operations.py +++ /dev/null @@ -1,376 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Literal, Optional, TypeVar, Union - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._service_operations import ( - build_get_properties_request, - build_get_user_delegation_key_request, - build_list_shares_segment_request, - build_set_properties_request, -) -from .._configuration import AzureFileStorageConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class ServiceOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare.aio.AzureFileStorage`'s - :attr:`service` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureFileStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def set_properties( - self, storage_service_properties: _models.StorageServiceProperties, timeout: Optional[int] = None, **kwargs: Any - ) -> None: - """Sets properties for a storage account's File service endpoint, including properties for Storage - Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. - - :param storage_service_properties: The StorageService properties. Required. - :type storage_service_properties: ~azure.storage.fileshare.models.StorageServiceProperties - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _content = self._serialize.body(storage_service_properties, "StorageServiceProperties", is_xml=True) - - _request = build_set_properties_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_properties(self, timeout: Optional[int] = None, **kwargs: Any) -> _models.StorageServiceProperties: - """Gets the properties of a storage account's File service, including properties for Storage - Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: StorageServiceProperties or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.StorageServiceProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - cls: ClsType[_models.StorageServiceProperties] = kwargs.pop("cls", None) - - _request = build_get_properties_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - - deserialized = self._deserialize("StorageServiceProperties", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_shares_segment( - self, - prefix: Optional[str] = None, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - include: Optional[list[Union[str, _models.ListSharesIncludeType]]] = None, - timeout: Optional[int] = None, - **kwargs: Any - ) -> _models.ListSharesResponse: - """The List Shares Segment operation returns a list of the shares and share snapshots under the - specified account. - - :param prefix: Filters the results to return only entries whose name begins with the specified - prefix. Default value is None. - :type prefix: str - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param maxresults: Specifies the maximum number of entries to return. If the request does not - specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 - items. Default value is None. - :type maxresults: int - :param include: Include this parameter to specify one or more datasets to include in the - response. Default value is None. - :type include: list[str or ~azure.storage.fileshare.models.ListSharesIncludeType] - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: ListSharesResponse or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ListSharesResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["list"] = kwargs.pop("comp", _params.pop("comp", "list")) - cls: ClsType[_models.ListSharesResponse] = kwargs.pop("cls", None) - - _request = build_list_shares_segment_request( - url=self._config.url, - version=self._config.version, - prefix=prefix, - marker=marker, - maxresults=maxresults, - include=include, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - - deserialized = self._deserialize("ListSharesResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_user_delegation_key( - self, - key_info: _models.KeyInfo, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> _models.UserDelegationKey: - """Retrieves a user delegation key for the File service. This is only a valid operation when using - bearer token authentication. - - :param key_info: Key information. Required. - :type key_info: ~azure.storage.fileshare.models.KeyInfo - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: UserDelegationKey or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.UserDelegationKey - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["userdelegationkey"] = kwargs.pop("comp", _params.pop("comp", "userdelegationkey")) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) - cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) - - _content = self._serialize.body(key_info, "KeyInfo", is_xml=True) - - _request = build_get_user_delegation_key_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - request_id_parameter=request_id_parameter, - restype=restype, - comp=comp, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("UserDelegationKey", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_share_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_share_operations.py deleted file mode 100644 index 39daa0cfeb65..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_share_operations.py +++ /dev/null @@ -1,1811 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload - -from azure.core import AsyncPipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.serialization import Deserializer, Serializer -from ...operations._share_operations import ( - build_acquire_lease_request, - build_break_lease_request, - build_change_lease_request, - build_create_permission_request, - build_create_request, - build_create_snapshot_request, - build_delete_request, - build_get_access_policy_request, - build_get_permission_request, - build_get_properties_request, - build_get_statistics_request, - build_release_lease_request, - build_renew_lease_request, - build_restore_request, - build_set_access_policy_request, - build_set_metadata_request, - build_set_properties_request, -) -from .._configuration import AzureFileStorageConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] - - -class ShareOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare.aio.AzureFileStorage`'s - :attr:`share` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureFileStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace_async - async def create( # pylint: disable=too-many-locals - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - quota: Optional[int] = None, - access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, - enabled_protocols: Optional[str] = None, - root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, - enable_snapshot_virtual_directory_access: Optional[bool] = None, - paid_bursting_enabled: Optional[bool] = None, - paid_bursting_max_bandwidth_mibps: Optional[int] = None, - paid_bursting_max_iops: Optional[int] = None, - share_provisioned_iops: Optional[int] = None, - share_provisioned_bandwidth_mibps: Optional[int] = None, - enable_smb_directory_lease: Optional[bool] = None, - **kwargs: Any - ) -> None: - """Creates a new share under the specified account. If the share with the same name already - exists, the operation fails. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param quota: Specifies the maximum size of the share, in gigabytes. Default value is None. - :type quota: int - :param access_tier: Specifies the access tier of the share. Known values are: - "TransactionOptimized", "Hot", "Cool", and "Premium". Default value is None. - :type access_tier: str or ~azure.storage.fileshare.models.ShareAccessTier - :param enabled_protocols: Protocols to enable on the share. Default value is None. - :type enabled_protocols: str - :param root_squash: Root squash to set on the share. Only valid for NFS shares. Known values - are: "NoRootSquash", "RootSquash", and "AllSquash". Default value is None. - :type root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash - :param enable_snapshot_virtual_directory_access: Default value is None. - :type enable_snapshot_virtual_directory_access: bool - :param paid_bursting_enabled: Optional. Boolean. Default if not specified is false. This - property enables paid bursting. Default value is None. - :type paid_bursting_enabled: bool - :param paid_bursting_max_bandwidth_mibps: Optional. Integer. Default if not specified is the - maximum throughput the file share can support. Current maximum for a file share is 10,340 - MiB/sec. Default value is None. - :type paid_bursting_max_bandwidth_mibps: int - :param paid_bursting_max_iops: Optional. Integer. Default if not specified is the maximum IOPS - the file share can support. Current maximum for a file share is 102,400 IOPS. Default value is - None. - :type paid_bursting_max_iops: int - :param share_provisioned_iops: Optional. Supported in version 2025-01-05 and later. Only - allowed for provisioned v2 file shares. Specifies the provisioned number of input/output - operations per second (IOPS) of the share. If this is not specified, the provisioned IOPS is - set to value calculated based on recommendation formula. Default value is None. - :type share_provisioned_iops: int - :param share_provisioned_bandwidth_mibps: Optional. Supported in version 2025-01-05 and later. - Only allowed for provisioned v2 file shares. Specifies the provisioned bandwidth of the share, - in mebibytes per second (MiBps). If this is not specified, the provisioned bandwidth is set to - value calculated based on recommendation formula. Default value is None. - :type share_provisioned_bandwidth_mibps: int - :param enable_smb_directory_lease: SMB only, default is true. Specifies whether granting of - new directory leases for directories present in a share are to be enabled or disabled. An input - of true specifies that granting of new directory leases is to be allowed. An input of false - specifies that granting of new directory leases is to be blocked. Default value is None. - :type enable_smb_directory_lease: bool - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_create_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - quota=quota, - access_tier=access_tier, - enabled_protocols=enabled_protocols, - root_squash=root_squash, - enable_snapshot_virtual_directory_access=enable_snapshot_virtual_directory_access, - paid_bursting_enabled=paid_bursting_enabled, - paid_bursting_max_bandwidth_mibps=paid_bursting_max_bandwidth_mibps, - paid_bursting_max_iops=paid_bursting_max_iops, - share_provisioned_iops=share_provisioned_iops, - share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, - enable_smb_directory_lease=enable_smb_directory_lease, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) - response_headers["x-ms-share-provisioned-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-iops") - ) - response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") - ) - response_headers["x-ms-share-included-burst-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-included-burst-iops") - ) - response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_properties( - self, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Returns all user-defined metadata and system properties for the specified share or share - snapshot. The data returned does not include the share's list of files. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_properties_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - timeout=timeout, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) - response_headers["x-ms-share-provisioned-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-iops") - ) - response_headers["x-ms-share-provisioned-ingress-mbps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-ingress-mbps") - ) - response_headers["x-ms-share-provisioned-egress-mbps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-egress-mbps") - ) - response_headers["x-ms-share-next-allowed-quota-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-quota-downgrade-time") - ) - response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") - ) - response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) - response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) - response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) - response_headers["x-ms-access-tier"] = self._deserialize("str", response.headers.get("x-ms-access-tier")) - response_headers["x-ms-access-tier-change-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-access-tier-change-time") - ) - response_headers["x-ms-access-tier-transition-state"] = self._deserialize( - "str", response.headers.get("x-ms-access-tier-transition-state") - ) - response_headers["x-ms-enabled-protocols"] = self._deserialize( - "str", response.headers.get("x-ms-enabled-protocols") - ) - response_headers["x-ms-root-squash"] = self._deserialize("str", response.headers.get("x-ms-root-squash")) - response_headers["x-ms-enable-snapshot-virtual-directory-access"] = self._deserialize( - "bool", response.headers.get("x-ms-enable-snapshot-virtual-directory-access") - ) - response_headers["x-ms-share-paid-bursting-enabled"] = self._deserialize( - "bool", response.headers.get("x-ms-share-paid-bursting-enabled") - ) - response_headers["x-ms-share-paid-bursting-max-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-paid-bursting-max-iops") - ) - response_headers["x-ms-share-paid-bursting-max-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-paid-bursting-max-bandwidth-mibps") - ) - response_headers["x-ms-share-included-burst-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-included-burst-iops") - ) - response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") - ) - response_headers["x-ms-share-next-allowed-provisioned-iops-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-iops-downgrade-time") - ) - response_headers["x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time") - ) - response_headers["x-ms-enable-smb-directory-lease"] = self._deserialize( - "bool", response.headers.get("x-ms-enable-smb-directory-lease") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def delete( - self, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Operation marks the specified share or share snapshot for deletion. The share or share snapshot - and any files contained within it are later deleted during garbage collection. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param delete_snapshots: Specifies the option include to delete the base share and all of its - snapshots. Known values are: "include" and "include-leased". Default value is None. - :type delete_snapshots: str or ~azure.storage.fileshare.models.DeleteSnapshotsOptionType - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_delete_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - timeout=timeout, - delete_snapshots=delete_snapshots, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-file-share-usage-bytes"] = self._deserialize( - "int", response.headers.get("x-ms-file-share-usage-bytes") - ) - response_headers["x-ms-file-share-snapshot-usage-bytes"] = self._deserialize( - "int", response.headers.get("x-ms-file-share-snapshot-usage-bytes") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def acquire_lease( - self, - timeout: Optional[int] = None, - duration: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param duration: Specifies the duration of the lease, in seconds, or negative one (-1) for a - lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease - duration cannot be changed using renew or change. Default value is None. - :type duration: int - :param proposed_lease_id: Proposed lease ID, in a GUID string format. The File service returns - 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid - Constructor (String) for a list of valid GUID string formats. Default value is None. - :type proposed_lease_id: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_acquire_lease_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - duration=duration, - proposed_lease_id=proposed_lease_id, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def release_lease( - self, - lease_id: str, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_release_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def change_lease( - self, - lease_id: str, - timeout: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param proposed_lease_id: Proposed lease ID, in a GUID string format. The File service returns - 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid - Constructor (String) for a list of valid GUID string formats. Default value is None. - :type proposed_lease_id: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_change_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - proposed_lease_id=proposed_lease_id, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def renew_lease( - self, - lease_id: str, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["renew"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "renew")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renew_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def break_lease( - self, - timeout: Optional[int] = None, - break_period: Optional[int] = None, - request_id_parameter: Optional[str] = None, - sharesnapshot: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param break_period: For a break operation, proposed duration the lease should continue before - it is broken, in seconds, between 0 and 60. This break period is only used if it is shorter - than the time remaining on the lease. If longer, the time remaining on the lease is used. A new - lease will not be available before the break period has expired, but the lease may be held for - longer than the break period. If this header does not appear with a break operation, a - fixed-duration lease breaks after the remaining lease period elapses, and an infinite lease - breaks immediately. Default value is None. - :type break_period: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_break_lease_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - break_period=break_period, - lease_id=_lease_id, - request_id_parameter=request_id_parameter, - sharesnapshot=sharesnapshot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-time"] = self._deserialize("int", response.headers.get("x-ms-lease-time")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def create_snapshot( - self, timeout: Optional[int] = None, metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> None: - """Creates a read-only snapshot of a share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["snapshot"] = kwargs.pop("comp", _params.pop("comp", "snapshot")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_create_snapshot_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-snapshot"] = self._deserialize("str", response.headers.get("x-ms-snapshot")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @overload - async def create_permission( - self, - share_permission: _models.SharePermission, - timeout: Optional[int] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Create a permission (a security descriptor). - - :param share_permission: A permission (a security descriptor) at the share level. Required. - :type share_permission: ~azure.storage.fileshare.models.SharePermission - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_permission( - self, - share_permission: IO[bytes], - timeout: Optional[int] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Create a permission (a security descriptor). - - :param share_permission: A permission (a security descriptor) at the share level. Required. - :type share_permission: IO[bytes] - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_permission( - self, share_permission: Union[_models.SharePermission, IO[bytes]], timeout: Optional[int] = None, **kwargs: Any - ) -> None: - """Create a permission (a security descriptor). - - :param share_permission: A permission (a security descriptor) at the share level. Is either a - SharePermission type or a IO[bytes] type. Required. - :type share_permission: ~azure.storage.fileshare.models.SharePermission or IO[bytes] - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["filepermission"] = kwargs.pop("comp", _params.pop("comp", "filepermission")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(share_permission, (IOBase, bytes)): - _content = share_permission - else: - _json = self._serialize.body(share_permission, "SharePermission") - - _request = build_create_permission_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_permission( - self, - file_permission_key: str, - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - timeout: Optional[int] = None, - **kwargs: Any - ) -> _models.SharePermission: - """Returns the permission (security descriptor) for a given key. - - :param file_permission_key: Key of the permission to be set for the directory/file. Required. - :type file_permission_key: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: SharePermission or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.SharePermission - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["filepermission"] = kwargs.pop("comp", _params.pop("comp", "filepermission")) - cls: ClsType[_models.SharePermission] = kwargs.pop("cls", None) - - _request = build_get_permission_request( - url=self._config.url, - file_permission_key=file_permission_key, - version=self._config.version, - file_permission_format=file_permission_format, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("SharePermission", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def set_properties( # pylint: disable=too-many-locals - self, - timeout: Optional[int] = None, - quota: Optional[int] = None, - access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, - root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, - enable_snapshot_virtual_directory_access: Optional[bool] = None, - paid_bursting_enabled: Optional[bool] = None, - paid_bursting_max_bandwidth_mibps: Optional[int] = None, - paid_bursting_max_iops: Optional[int] = None, - share_provisioned_iops: Optional[int] = None, - share_provisioned_bandwidth_mibps: Optional[int] = None, - enable_smb_directory_lease: Optional[bool] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Sets properties for the specified share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param quota: Specifies the maximum size of the share, in gigabytes. Default value is None. - :type quota: int - :param access_tier: Specifies the access tier of the share. Known values are: - "TransactionOptimized", "Hot", "Cool", and "Premium". Default value is None. - :type access_tier: str or ~azure.storage.fileshare.models.ShareAccessTier - :param root_squash: Root squash to set on the share. Only valid for NFS shares. Known values - are: "NoRootSquash", "RootSquash", and "AllSquash". Default value is None. - :type root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash - :param enable_snapshot_virtual_directory_access: Default value is None. - :type enable_snapshot_virtual_directory_access: bool - :param paid_bursting_enabled: Optional. Boolean. Default if not specified is false. This - property enables paid bursting. Default value is None. - :type paid_bursting_enabled: bool - :param paid_bursting_max_bandwidth_mibps: Optional. Integer. Default if not specified is the - maximum throughput the file share can support. Current maximum for a file share is 10,340 - MiB/sec. Default value is None. - :type paid_bursting_max_bandwidth_mibps: int - :param paid_bursting_max_iops: Optional. Integer. Default if not specified is the maximum IOPS - the file share can support. Current maximum for a file share is 102,400 IOPS. Default value is - None. - :type paid_bursting_max_iops: int - :param share_provisioned_iops: Optional. Supported in version 2025-01-05 and later. Only - allowed for provisioned v2 file shares. Specifies the provisioned number of input/output - operations per second (IOPS) of the share. If this is not specified, the provisioned IOPS is - set to value calculated based on recommendation formula. Default value is None. - :type share_provisioned_iops: int - :param share_provisioned_bandwidth_mibps: Optional. Supported in version 2025-01-05 and later. - Only allowed for provisioned v2 file shares. Specifies the provisioned bandwidth of the share, - in mebibytes per second (MiBps). If this is not specified, the provisioned bandwidth is set to - value calculated based on recommendation formula. Default value is None. - :type share_provisioned_bandwidth_mibps: int - :param enable_smb_directory_lease: SMB only, default is true. Specifies whether granting of - new directory leases for directories present in a share are to be enabled or disabled. An input - of true specifies that granting of new directory leases is to be allowed. An input of false - specifies that granting of new directory leases is to be blocked. Default value is None. - :type enable_smb_directory_lease: bool - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_set_properties_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - quota=quota, - access_tier=access_tier, - lease_id=_lease_id, - root_squash=root_squash, - enable_snapshot_virtual_directory_access=enable_snapshot_virtual_directory_access, - paid_bursting_enabled=paid_bursting_enabled, - paid_bursting_max_bandwidth_mibps=paid_bursting_max_bandwidth_mibps, - paid_bursting_max_iops=paid_bursting_max_iops, - share_provisioned_iops=share_provisioned_iops, - share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, - enable_smb_directory_lease=enable_smb_directory_lease, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) - response_headers["x-ms-share-provisioned-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-iops") - ) - response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") - ) - response_headers["x-ms-share-included-burst-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-included-burst-iops") - ) - response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") - ) - response_headers["x-ms-share-next-allowed-quota-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-quota-downgrade-time") - ) - response_headers["x-ms-share-next-allowed-provisioned-iops-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-iops-downgrade-time") - ) - response_headers["x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def set_metadata( - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Sets one or more user-defined name-value pairs for the specified share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_set_metadata_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_access_policy( - self, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> list[_models.SignedIdentifier]: - """Returns information about stored access policies specified on the share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: list of SignedIdentifier or the result of cls(response) - :rtype: list[~azure.storage.fileshare.models.SignedIdentifier] - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - cls: ClsType[list[_models.SignedIdentifier]] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_access_policy_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("[SignedIdentifier]", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def set_access_policy( - self, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - share_acl: Optional[list[_models.SignedIdentifier]] = None, - **kwargs: Any - ) -> None: - """Sets a stored access policy for use with shared access signatures. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :param share_acl: The ACL for the share. Default value is None. - :type share_acl: list[~azure.storage.fileshare.models.SignedIdentifier] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) - content_type = content_type if share_acl else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - serialization_ctxt = {"xml": {"name": "SignedIdentifiers", "wrapped": True}} - if share_acl is not None: - _content = self._serialize.body( - share_acl, "[SignedIdentifier]", is_xml=True, serialization_ctxt=serialization_ctxt - ) - else: - _content = None - - _request = build_set_access_policy_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace_async - async def get_statistics( - self, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> _models.ShareStats: - """Retrieves statistics related to the share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: ShareStats or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ShareStats - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["stats"] = kwargs.pop("comp", _params.pop("comp", "stats")) - cls: ClsType[_models.ShareStats] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_statistics_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ShareStats", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def restore( - self, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - deleted_share_name: Optional[str] = None, - deleted_share_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """Restores a previously deleted Share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param deleted_share_name: Specifies the name of the previously-deleted share. Default value is - None. - :type deleted_share_name: str - :param deleted_share_version: Specifies the version of the previously-deleted share. Default - value is None. - :type deleted_share_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["undelete"] = kwargs.pop("comp", _params.pop("comp", "undelete")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_restore_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - request_id_parameter=request_id_parameter, - deleted_share_name=deleted_share_name, - deleted_share_version=deleted_share_version, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) - response_headers["x-ms-share-provisioned-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-iops") - ) - response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") - ) - response_headers["x-ms-share-included-burst-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-included-burst-iops") - ) - response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/__init__.py index bb6fe56afaca..9a1f11643f63 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -13,21 +13,18 @@ from ._patch import * # pylint: disable=unused-wildcard-import -from ._models_py3 import ( # type: ignore +from ._models import ( # type: ignore AccessPolicy, ClearRange, - CopyFileSmbInfo, CorsRule, - DestinationLeaseAccessConditions, DirectoryItem, - FileHTTPHeaders, + Error, FileItem, FileProperty, FileRange, FilesAndDirectoriesListSegment, HandleItem, KeyInfo, - LeaseAccessConditions, ListFilesAndDirectoriesSegmentResponse, ListHandlesResponse, ListSharesResponse, @@ -44,22 +41,21 @@ ShareSmbSettingsEncryptionInTransit, ShareStats, SignedIdentifier, + SignedIdentifiers, SmbMultichannel, - SourceLeaseAccessConditions, - SourceModifiedAccessConditions, - StorageError, StorageServiceProperties, StringEncoded, UserDelegationKey, ) -from ._azure_file_storage_enums import ( # type: ignore +from ._enums import ( # type: ignore AccessRight, - CopyStatusType, + CopyStatus, DeleteSnapshotsOptionType, FileLastWrittenMode, FilePermissionFormat, FilePropertySemantics, + FileRangeWriteFromUrlType, FileRangeWriteType, LeaseDurationType, LeaseStateType, @@ -82,18 +78,15 @@ __all__ = [ "AccessPolicy", "ClearRange", - "CopyFileSmbInfo", "CorsRule", - "DestinationLeaseAccessConditions", "DirectoryItem", - "FileHTTPHeaders", + "Error", "FileItem", "FileProperty", "FileRange", "FilesAndDirectoriesListSegment", "HandleItem", "KeyInfo", - "LeaseAccessConditions", "ListFilesAndDirectoriesSegmentResponse", "ListHandlesResponse", "ListSharesResponse", @@ -110,19 +103,18 @@ "ShareSmbSettingsEncryptionInTransit", "ShareStats", "SignedIdentifier", + "SignedIdentifiers", "SmbMultichannel", - "SourceLeaseAccessConditions", - "SourceModifiedAccessConditions", - "StorageError", "StorageServiceProperties", "StringEncoded", "UserDelegationKey", "AccessRight", - "CopyStatusType", + "CopyStatus", "DeleteSnapshotsOptionType", "FileLastWrittenMode", "FilePermissionFormat", "FilePropertySemantics", + "FileRangeWriteFromUrlType", "FileRangeWriteType", "LeaseDurationType", "LeaseStateType", diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_azure_file_storage_enums.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_enums.py similarity index 60% rename from sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_azure_file_storage_enums.py rename to sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_enums.py index 34c21387336a..a2732c2608da 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_azure_file_storage_enums.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_enums.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- @@ -14,224 +14,363 @@ class AccessRight(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Access rights of the access policy.""" READ = "Read" + """Read.""" WRITE = "Write" + """Write.""" DELETE = "Delete" + """Delete.""" -class CopyStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """CopyStatusType.""" +class CopyStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The copy status.""" PENDING = "pending" + """The copy operation is pending.""" SUCCESS = "success" + """The copy operation succeeded.""" ABORTED = "aborted" + """The copy operation was aborted.""" FAILED = "failed" + """The copy operation failed.""" class DeleteSnapshotsOptionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """DeleteSnapshotsOptionType.""" + """The delete snapshots option type.""" INCLUDE = "include" + """include.""" INCLUDE_LEASED = "include-leased" + """include-leased.""" class FileLastWrittenMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """FileLastWrittenMode.""" + """The file last written mode.""" NOW = "Now" + """Now.""" PRESERVE = "Preserve" + """Preserve.""" class FilePermissionFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """FilePermissionFormat.""" + """The file permission format.""" SDDL = "Sddl" + """Sddl.""" BINARY = "Binary" + """Binary.""" class FilePropertySemantics(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """FilePropertySemantics.""" + """The file property semantics.""" NEW = "New" + """New.""" RESTORE = "Restore" + """Restore.""" + + +class FileRangeWriteFromUrlType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Only update is supported: - Update: Writes the bytes downloaded from the source url into the + specified range. + """ + + UPDATE = "update" + """Writes the bytes specified by the source URL into the specified range.""" class FileRangeWriteType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """FileRangeWriteType.""" + """Specify one of the following options: - Update: Writes the bytes specified by the request body + into the specified range. - Clear: Clears the specified range and releases the space used in + storage for that range. + """ UPDATE = "update" + """Writes the bytes specified by the request body into the specified range.""" CLEAR = "clear" + """Clears the specified range and releases the space used in storage for that range.""" class LeaseDurationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """When a share is leased, specifies whether the lease is of infinite or fixed duration.""" INFINITE = "infinite" + """infinite.""" FIXED = "fixed" + """fixed.""" class LeaseStateType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Lease state of the share.""" AVAILABLE = "available" + """available.""" LEASED = "leased" + """leased.""" EXPIRED = "expired" + """expired.""" BREAKING = "breaking" + """breaking.""" BROKEN = "broken" + """broken.""" class LeaseStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The current lease status of the share.""" LOCKED = "locked" + """locked.""" UNLOCKED = "unlocked" + """unlocked.""" class ListFilesIncludeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ListFilesIncludeType.""" + """The type of file information to include in the listing.""" TIMESTAMPS = "Timestamps" + """Timestamps.""" ETAG = "Etag" + """Etag.""" ATTRIBUTES = "Attributes" + """Attributes.""" PERMISSION_KEY = "PermissionKey" + """PermissionKey.""" class ListSharesIncludeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ListSharesIncludeType.""" + """The type of share information to include in the listing.""" SNAPSHOTS = "snapshots" + """snapshots.""" METADATA = "metadata" + """metadata.""" DELETED = "deleted" + """deleted.""" class ModeCopyMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ModeCopyMode.""" + """The mode copy mode.""" SOURCE = "source" + """source.""" OVERRIDE = "override" + """override.""" class NfsFileType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """NfsFileType.""" + """The NFS file type.""" REGULAR = "Regular" + """Regular.""" DIRECTORY = "Directory" + """Directory.""" SYM_LINK = "SymLink" + """SymLink.""" class OwnerCopyMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """OwnerCopyMode.""" + """The owner copy mode.""" SOURCE = "source" + """source.""" OVERRIDE = "override" + """override.""" class PermissionCopyModeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """PermissionCopyModeType.""" + """The permission copy mode type.""" SOURCE = "source" + """source.""" OVERRIDE = "override" + """override.""" class ShareAccessTier(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ShareAccessTier.""" + """The access tier of the share.""" TRANSACTION_OPTIMIZED = "TransactionOptimized" + """TransactionOptimized.""" HOT = "Hot" + """Hot.""" COOL = "Cool" + """Cool.""" PREMIUM = "Premium" + """Premium.""" class ShareRootSquash(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ShareRootSquash.""" + """The root squash setting for the share.""" NO_ROOT_SQUASH = "NoRootSquash" + """NoRootSquash.""" ROOT_SQUASH = "RootSquash" + """RootSquash.""" ALL_SQUASH = "AllSquash" + """AllSquash.""" class ShareTokenIntent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ShareTokenIntent.""" + """The share token intent.""" BACKUP = "backup" + """backup.""" class StorageErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Error codes returned by the service.""" ACCOUNT_ALREADY_EXISTS = "AccountAlreadyExists" + """AccountAlreadyExists.""" ACCOUNT_BEING_CREATED = "AccountBeingCreated" + """AccountBeingCreated.""" ACCOUNT_IS_DISABLED = "AccountIsDisabled" + """AccountIsDisabled.""" AUTHENTICATION_FAILED = "AuthenticationFailed" + """AuthenticationFailed.""" AUTHORIZATION_FAILURE = "AuthorizationFailure" + """AuthorizationFailure.""" CONDITION_HEADERS_NOT_SUPPORTED = "ConditionHeadersNotSupported" + """ConditionHeadersNotSupported.""" CONDITION_NOT_MET = "ConditionNotMet" + """ConditionNotMet.""" EMPTY_METADATA_KEY = "EmptyMetadataKey" + """EmptyMetadataKey.""" FILE_SHARE_PROVISIONED_BANDWIDTH_DOWNGRADE_NOT_ALLOWED = "FileShareProvisionedBandwidthDowngradeNotAllowed" + """FileShareProvisionedBandwidthDowngradeNotAllowed.""" FILE_SHARE_PROVISIONED_IOPS_DOWNGRADE_NOT_ALLOWED = "FileShareProvisionedIopsDowngradeNotAllowed" + """FileShareProvisionedIopsDowngradeNotAllowed.""" INSUFFICIENT_ACCOUNT_PERMISSIONS = "InsufficientAccountPermissions" + """InsufficientAccountPermissions.""" INTERNAL_ERROR = "InternalError" + """InternalError.""" INVALID_AUTHENTICATION_INFO = "InvalidAuthenticationInfo" + """InvalidAuthenticationInfo.""" INVALID_HEADER_VALUE = "InvalidHeaderValue" + """InvalidHeaderValue.""" INVALID_HTTP_VERB = "InvalidHttpVerb" + """InvalidHttpVerb.""" INVALID_INPUT = "InvalidInput" + """InvalidInput.""" INVALID_MD5 = "InvalidMd5" + """InvalidMd5.""" INVALID_METADATA = "InvalidMetadata" + """InvalidMetadata.""" INVALID_QUERY_PARAMETER_VALUE = "InvalidQueryParameterValue" + """InvalidQueryParameterValue.""" INVALID_RANGE = "InvalidRange" + """InvalidRange.""" INVALID_RESOURCE_NAME = "InvalidResourceName" + """InvalidResourceName.""" INVALID_URI = "InvalidUri" + """InvalidUri.""" INVALID_XML_DOCUMENT = "InvalidXmlDocument" + """InvalidXmlDocument.""" INVALID_XML_NODE_VALUE = "InvalidXmlNodeValue" + """InvalidXmlNodeValue.""" MD5_MISMATCH = "Md5Mismatch" + """Md5Mismatch.""" METADATA_TOO_LARGE = "MetadataTooLarge" + """MetadataTooLarge.""" MISSING_CONTENT_LENGTH_HEADER = "MissingContentLengthHeader" + """MissingContentLengthHeader.""" MISSING_REQUIRED_QUERY_PARAMETER = "MissingRequiredQueryParameter" + """MissingRequiredQueryParameter.""" MISSING_REQUIRED_HEADER = "MissingRequiredHeader" + """MissingRequiredHeader.""" MISSING_REQUIRED_XML_NODE = "MissingRequiredXmlNode" + """MissingRequiredXmlNode.""" MULTIPLE_CONDITION_HEADERS_NOT_SUPPORTED = "MultipleConditionHeadersNotSupported" + """MultipleConditionHeadersNotSupported.""" OPERATION_TIMED_OUT = "OperationTimedOut" + """OperationTimedOut.""" OUT_OF_RANGE_INPUT = "OutOfRangeInput" + """OutOfRangeInput.""" OUT_OF_RANGE_QUERY_PARAMETER_VALUE = "OutOfRangeQueryParameterValue" + """OutOfRangeQueryParameterValue.""" REQUEST_BODY_TOO_LARGE = "RequestBodyTooLarge" + """RequestBodyTooLarge.""" RESOURCE_TYPE_MISMATCH = "ResourceTypeMismatch" + """ResourceTypeMismatch.""" REQUEST_URL_FAILED_TO_PARSE = "RequestUrlFailedToParse" + """RequestUrlFailedToParse.""" RESOURCE_ALREADY_EXISTS = "ResourceAlreadyExists" + """ResourceAlreadyExists.""" RESOURCE_NOT_FOUND = "ResourceNotFound" + """ResourceNotFound.""" SERVER_BUSY = "ServerBusy" + """ServerBusy.""" UNSUPPORTED_HEADER = "UnsupportedHeader" + """UnsupportedHeader.""" UNSUPPORTED_XML_NODE = "UnsupportedXmlNode" + """UnsupportedXmlNode.""" UNSUPPORTED_QUERY_PARAMETER = "UnsupportedQueryParameter" + """UnsupportedQueryParameter.""" UNSUPPORTED_HTTP_VERB = "UnsupportedHttpVerb" + """UnsupportedHttpVerb.""" CANNOT_DELETE_FILE_OR_DIRECTORY = "CannotDeleteFileOrDirectory" + """CannotDeleteFileOrDirectory.""" CLIENT_CACHE_FLUSH_DELAY = "ClientCacheFlushDelay" + """ClientCacheFlushDelay.""" DELETE_PENDING = "DeletePending" + """DeletePending.""" DIRECTORY_NOT_EMPTY = "DirectoryNotEmpty" + """DirectoryNotEmpty.""" FILE_LOCK_CONFLICT = "FileLockConflict" + """FileLockConflict.""" INVALID_FILE_OR_DIRECTORY_PATH_NAME = "InvalidFileOrDirectoryPathName" + """InvalidFileOrDirectoryPathName.""" PARENT_NOT_FOUND = "ParentNotFound" + """ParentNotFound.""" READ_ONLY_ATTRIBUTE = "ReadOnlyAttribute" + """ReadOnlyAttribute.""" SHARE_ALREADY_EXISTS = "ShareAlreadyExists" + """ShareAlreadyExists.""" SHARE_BEING_DELETED = "ShareBeingDeleted" + """ShareBeingDeleted.""" SHARE_DISABLED = "ShareDisabled" + """ShareDisabled.""" SHARE_NOT_FOUND = "ShareNotFound" + """ShareNotFound.""" SHARING_VIOLATION = "SharingViolation" + """SharingViolation.""" SHARE_SNAPSHOT_IN_PROGRESS = "ShareSnapshotInProgress" + """ShareSnapshotInProgress.""" SHARE_SNAPSHOT_COUNT_EXCEEDED = "ShareSnapshotCountExceeded" + """ShareSnapshotCountExceeded.""" SHARE_SNAPSHOT_OPERATION_NOT_SUPPORTED = "ShareSnapshotOperationNotSupported" + """ShareSnapshotOperationNotSupported.""" SHARE_HAS_SNAPSHOTS = "ShareHasSnapshots" + """ShareHasSnapshots.""" PREVIOUS_SNAPSHOT_NOT_FOUND = "PreviousSnapshotNotFound" + """PreviousSnapshotNotFound.""" CONTAINER_QUOTA_DOWNGRADE_NOT_ALLOWED = "ContainerQuotaDowngradeNotAllowed" + """ContainerQuotaDowngradeNotAllowed.""" AUTHORIZATION_SOURCE_IP_MISMATCH = "AuthorizationSourceIPMismatch" + """AuthorizationSourceIPMismatch.""" AUTHORIZATION_PROTOCOL_MISMATCH = "AuthorizationProtocolMismatch" + """AuthorizationProtocolMismatch.""" AUTHORIZATION_PERMISSION_MISMATCH = "AuthorizationPermissionMismatch" + """AuthorizationPermissionMismatch.""" AUTHORIZATION_SERVICE_MISMATCH = "AuthorizationServiceMismatch" + """AuthorizationServiceMismatch.""" AUTHORIZATION_RESOURCE_TYPE_MISMATCH = "AuthorizationResourceTypeMismatch" + """AuthorizationResourceTypeMismatch.""" FEATURE_VERSION_MISMATCH = "FeatureVersionMismatch" + """FeatureVersionMismatch.""" SHARE_SNAPSHOT_NOT_FOUND = "ShareSnapshotNotFound" + """ShareSnapshotNotFound.""" FILE_SHARE_PROVISIONED_IOPS_INVALID = "FileShareProvisionedIopsInvalid" + """FileShareProvisionedIopsInvalid.""" FILE_SHARE_PROVISIONED_BANDWIDTH_INVALID = "FileShareProvisionedBandwidthInvalid" + """FileShareProvisionedBandwidthInvalid.""" FILE_SHARE_PROVISIONED_STORAGE_INVALID = "FileShareProvisionedStorageInvalid" + """FileShareProvisionedStorageInvalid.""" TOTAL_SHARES_PROVISIONED_CAPACITY_EXCEEDS_ACCOUNT_LIMIT = "TotalSharesProvisionedCapacityExceedsAccountLimit" + """TotalSharesProvisionedCapacityExceedsAccountLimit.""" TOTAL_SHARES_PROVISIONED_IOPS_EXCEEDS_ACCOUNT_LIMIT = "TotalSharesProvisionedIopsExceedsAccountLimit" + """TotalSharesProvisionedIopsExceedsAccountLimit.""" TOTAL_SHARES_PROVISIONED_BANDWIDTH_EXCEEDS_ACCOUNT_LIMIT = "TotalSharesProvisionedBandwidthExceedsAccountLimit" + """TotalSharesProvisionedBandwidthExceedsAccountLimit.""" TOTAL_SHARES_COUNT_EXCEEDS_ACCOUNT_LIMIT = "TotalSharesCountExceedsAccountLimit" + """TotalSharesCountExceedsAccountLimit.""" diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models.py new file mode 100644 index 000000000000..f58d1ee830ca --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models.py @@ -0,0 +1,2125 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation + +import datetime +from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload + +from .._utils.model_base import Model as _Model, rest_field + +if TYPE_CHECKING: + from .. import models as _models + + +class AccessPolicy(_Model): + """An Access policy. + + :ivar start: The date-time the policy is active. + :vartype start: str + :ivar expiry: The date-time the policy expires. + :vartype expiry: str + :ivar permission: The permissions for the ACL policy. + :vartype permission: str + """ + + start: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + ) + """The date-time the policy is active.""" + expiry: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, + ) + """The date-time the policy expires.""" + permission: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Permission", "text": False, "unwrapped": False}, + ) + """The permissions for the ACL policy.""" + + _xml = {"attribute": False, "name": "AccessPolicy", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + start: Optional[str] = None, + expiry: Optional[str] = None, + permission: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ClearRange(_Model): + """A clear range. + + :ivar start: Start of the range. Required. + :vartype start: int + :ivar end: End of the range. Required. + :vartype end: int + """ + + start: int = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + ) + """Start of the range. Required.""" + end: int = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "End", "text": False, "unwrapped": False}, + ) + """End of the range. Required.""" + + _xml = {"attribute": False, "name": "ClearRange", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + start: int, + end: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class CorsRule(_Model): + """CORS is an HTTP feature that enables a web application running under one domain to access + resources in another domain. Web browsers implement a security restriction known as same-origin + policy that prevents a web page from calling APIs in a different domain; CORS provides a secure + way to allow one domain (the origin domain) to call APIs in another domain. + + :ivar allowed_origins: The origin domains that are permitted to make a request against the + storage service via CORS. The origin domain is the domain from which the request originates. + Note that the origin must be an exact case-sensitive match with the origin that the user age + sends to the service. You can also use the wildcard character '*' to allow all origin domains + to make requests via CORS. Required. + :vartype allowed_origins: str + :ivar allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a + CORS request. (comma separated). Required. + :vartype allowed_methods: str + :ivar allowed_headers: The request headers that the origin domain may specify on the CORS + request. Required. + :vartype allowed_headers: str + :ivar exposed_headers: The response headers that may be sent in the response to the CORS + request and exposed by the browser to the request issuer. Required. + :vartype exposed_headers: str + :ivar max_age_in_seconds: The maximum amount time that a browser should cache the preflight + OPTIONS request. Required. + :vartype max_age_in_seconds: int + """ + + allowed_origins: str = rest_field( + name="allowedOrigins", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AllowedOrigins", "text": False, "unwrapped": False}, + ) + """The origin domains that are permitted to make a request against the storage service via CORS. + The origin domain is the domain from which the request originates. Note that the origin must be + an exact case-sensitive match with the origin that the user age sends to the service. You can + also use the wildcard character '*' to allow all origin domains to make requests via CORS. + Required.""" + allowed_methods: str = rest_field( + name="allowedMethods", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AllowedMethods", "text": False, "unwrapped": False}, + ) + """The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma + separated). Required.""" + allowed_headers: str = rest_field( + name="allowedHeaders", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AllowedHeaders", "text": False, "unwrapped": False}, + ) + """The request headers that the origin domain may specify on the CORS request. Required.""" + exposed_headers: str = rest_field( + name="exposedHeaders", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ExposedHeaders", "text": False, "unwrapped": False}, + ) + """The response headers that may be sent in the response to the CORS request and exposed by the + browser to the request issuer. Required.""" + max_age_in_seconds: int = rest_field( + name="maxAgeInSeconds", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MaxAgeInSeconds", "text": False, "unwrapped": False}, + ) + """The maximum amount time that a browser should cache the preflight OPTIONS request. Required.""" + + _xml = {"attribute": False, "name": "CorsRule", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + allowed_origins: str, + allowed_methods: str, + allowed_headers: str, + exposed_headers: str, + max_age_in_seconds: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DirectoryItem(_Model): + """A listed directory item. + + :ivar name: The directory name. Required. + :vartype name: ~azure.storage.fileshare._generated.models.StringEncoded + :ivar file_id: The file ID. + :vartype file_id: str + :ivar properties: File properties. + :vartype properties: ~azure.storage.fileshare._generated.models.FileProperty + :ivar attributes: The file attributes. + :vartype attributes: str + :ivar permission_key: The permission key. + :vartype permission_key: str + """ + + name: "_models.StringEncoded" = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Name", "text": False, "unwrapped": False}, + ) + """The directory name. Required.""" + file_id: Optional[str] = rest_field( + name="fileId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "FileId", "text": False, "unwrapped": False}, + ) + """The file ID.""" + properties: Optional["_models.FileProperty"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Properties", "text": False, "unwrapped": False}, + ) + """File properties.""" + attributes: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Attributes", "text": False, "unwrapped": False}, + ) + """The file attributes.""" + permission_key: Optional[str] = rest_field( + name="permissionKey", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "PermissionKey", "text": False, "unwrapped": False}, + ) + """The permission key.""" + + _xml = {"attribute": False, "name": "Directory", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + name: "_models.StringEncoded", + file_id: Optional[str] = None, + properties: Optional["_models.FileProperty"] = None, + attributes: Optional[str] = None, + permission_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Error(_Model): + """The error response. + + This defines the wire format only. Language SDKs wrap this in idiomatic error types. + + :ivar code: The error code. Known values are: "AccountAlreadyExists", "AccountBeingCreated", + "AccountIsDisabled", "AuthenticationFailed", "AuthorizationFailure", + "ConditionHeadersNotSupported", "ConditionNotMet", "EmptyMetadataKey", + "FileShareProvisionedBandwidthDowngradeNotAllowed", + "FileShareProvisionedIopsDowngradeNotAllowed", "InsufficientAccountPermissions", + "InternalError", "InvalidAuthenticationInfo", "InvalidHeaderValue", "InvalidHttpVerb", + "InvalidInput", "InvalidMd5", "InvalidMetadata", "InvalidQueryParameterValue", "InvalidRange", + "InvalidResourceName", "InvalidUri", "InvalidXmlDocument", "InvalidXmlNodeValue", + "Md5Mismatch", "MetadataTooLarge", "MissingContentLengthHeader", + "MissingRequiredQueryParameter", "MissingRequiredHeader", "MissingRequiredXmlNode", + "MultipleConditionHeadersNotSupported", "OperationTimedOut", "OutOfRangeInput", + "OutOfRangeQueryParameterValue", "RequestBodyTooLarge", "ResourceTypeMismatch", + "RequestUrlFailedToParse", "ResourceAlreadyExists", "ResourceNotFound", "ServerBusy", + "UnsupportedHeader", "UnsupportedXmlNode", "UnsupportedQueryParameter", "UnsupportedHttpVerb", + "CannotDeleteFileOrDirectory", "ClientCacheFlushDelay", "DeletePending", "DirectoryNotEmpty", + "FileLockConflict", "InvalidFileOrDirectoryPathName", "ParentNotFound", "ReadOnlyAttribute", + "ShareAlreadyExists", "ShareBeingDeleted", "ShareDisabled", "ShareNotFound", + "SharingViolation", "ShareSnapshotInProgress", "ShareSnapshotCountExceeded", + "ShareSnapshotOperationNotSupported", "ShareHasSnapshots", "PreviousSnapshotNotFound", + "ContainerQuotaDowngradeNotAllowed", "AuthorizationSourceIPMismatch", + "AuthorizationProtocolMismatch", "AuthorizationPermissionMismatch", + "AuthorizationServiceMismatch", "AuthorizationResourceTypeMismatch", "FeatureVersionMismatch", + "ShareSnapshotNotFound", "FileShareProvisionedIopsInvalid", + "FileShareProvisionedBandwidthInvalid", "FileShareProvisionedStorageInvalid", + "TotalSharesProvisionedCapacityExceedsAccountLimit", + "TotalSharesProvisionedIopsExceedsAccountLimit", + "TotalSharesProvisionedBandwidthExceedsAccountLimit", and + "TotalSharesCountExceedsAccountLimit". + :vartype code: str or ~azure.storage.fileshare.models.StorageErrorCode + :ivar message: The error message. + :vartype message: str + :ivar copy_source_status_code: Copy source status code. + :vartype copy_source_status_code: int + :ivar copy_source_error_code: Copy source error code. + :vartype copy_source_error_code: str + :ivar copy_source_error_message: Copy source error message. + :vartype copy_source_error_message: str + """ + + code: Optional[Union[str, "_models.StorageErrorCode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Code", "text": False, "unwrapped": False}, + ) + """The error code. Known values are: \"AccountAlreadyExists\", \"AccountBeingCreated\", + \"AccountIsDisabled\", \"AuthenticationFailed\", \"AuthorizationFailure\", + \"ConditionHeadersNotSupported\", \"ConditionNotMet\", \"EmptyMetadataKey\", + \"FileShareProvisionedBandwidthDowngradeNotAllowed\", + \"FileShareProvisionedIopsDowngradeNotAllowed\", \"InsufficientAccountPermissions\", + \"InternalError\", \"InvalidAuthenticationInfo\", \"InvalidHeaderValue\", \"InvalidHttpVerb\", + \"InvalidInput\", \"InvalidMd5\", \"InvalidMetadata\", \"InvalidQueryParameterValue\", + \"InvalidRange\", \"InvalidResourceName\", \"InvalidUri\", \"InvalidXmlDocument\", + \"InvalidXmlNodeValue\", \"Md5Mismatch\", \"MetadataTooLarge\", \"MissingContentLengthHeader\", + \"MissingRequiredQueryParameter\", \"MissingRequiredHeader\", \"MissingRequiredXmlNode\", + \"MultipleConditionHeadersNotSupported\", \"OperationTimedOut\", \"OutOfRangeInput\", + \"OutOfRangeQueryParameterValue\", \"RequestBodyTooLarge\", \"ResourceTypeMismatch\", + \"RequestUrlFailedToParse\", \"ResourceAlreadyExists\", \"ResourceNotFound\", \"ServerBusy\", + \"UnsupportedHeader\", \"UnsupportedXmlNode\", \"UnsupportedQueryParameter\", + \"UnsupportedHttpVerb\", \"CannotDeleteFileOrDirectory\", \"ClientCacheFlushDelay\", + \"DeletePending\", \"DirectoryNotEmpty\", \"FileLockConflict\", + \"InvalidFileOrDirectoryPathName\", \"ParentNotFound\", \"ReadOnlyAttribute\", + \"ShareAlreadyExists\", \"ShareBeingDeleted\", \"ShareDisabled\", \"ShareNotFound\", + \"SharingViolation\", \"ShareSnapshotInProgress\", \"ShareSnapshotCountExceeded\", + \"ShareSnapshotOperationNotSupported\", \"ShareHasSnapshots\", \"PreviousSnapshotNotFound\", + \"ContainerQuotaDowngradeNotAllowed\", \"AuthorizationSourceIPMismatch\", + \"AuthorizationProtocolMismatch\", \"AuthorizationPermissionMismatch\", + \"AuthorizationServiceMismatch\", \"AuthorizationResourceTypeMismatch\", + \"FeatureVersionMismatch\", \"ShareSnapshotNotFound\", \"FileShareProvisionedIopsInvalid\", + \"FileShareProvisionedBandwidthInvalid\", \"FileShareProvisionedStorageInvalid\", + \"TotalSharesProvisionedCapacityExceedsAccountLimit\", + \"TotalSharesProvisionedIopsExceedsAccountLimit\", + \"TotalSharesProvisionedBandwidthExceedsAccountLimit\", and + \"TotalSharesCountExceedsAccountLimit\".""" + message: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Message", "text": False, "unwrapped": False}, + ) + """The error message.""" + copy_source_status_code: Optional[int] = rest_field( + name="copySourceStatusCode", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "CopySourceStatusCode", "text": False, "unwrapped": False}, + ) + """Copy source status code.""" + copy_source_error_code: Optional[str] = rest_field( + name="copySourceErrorCode", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "CopySourceErrorCode", "text": False, "unwrapped": False}, + ) + """Copy source error code.""" + copy_source_error_message: Optional[str] = rest_field( + name="copySourceErrorMessage", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "CopySourceErrorMessage", "text": False, "unwrapped": False}, + ) + """Copy source error message.""" + + _xml = {"attribute": False, "name": "Error", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + code: Optional[Union[str, "_models.StorageErrorCode"]] = None, + message: Optional[str] = None, + copy_source_status_code: Optional[int] = None, + copy_source_error_code: Optional[str] = None, + copy_source_error_message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FileItem(_Model): + """A listed file item. + + :ivar name: The file name. Required. + :vartype name: ~azure.storage.fileshare._generated.models.StringEncoded + :ivar file_id: The file ID. + :vartype file_id: str + :ivar properties: File properties. Required. + :vartype properties: ~azure.storage.fileshare._generated.models.FileProperty + :ivar attributes: The file attributes. + :vartype attributes: str + :ivar permission_key: The permission key. + :vartype permission_key: str + """ + + name: "_models.StringEncoded" = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Name", "text": False, "unwrapped": False}, + ) + """The file name. Required.""" + file_id: Optional[str] = rest_field( + name="fileId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "FileId", "text": False, "unwrapped": False}, + ) + """The file ID.""" + properties: "_models.FileProperty" = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Properties", "text": False, "unwrapped": False}, + ) + """File properties. Required.""" + attributes: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Attributes", "text": False, "unwrapped": False}, + ) + """The file attributes.""" + permission_key: Optional[str] = rest_field( + name="permissionKey", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "PermissionKey", "text": False, "unwrapped": False}, + ) + """The permission key.""" + + _xml = {"attribute": False, "name": "File", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + name: "_models.StringEncoded", + properties: "_models.FileProperty", + file_id: Optional[str] = None, + attributes: Optional[str] = None, + permission_key: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FileProperty(_Model): + """File properties. + + :ivar content_length: Content length of the file. This value may not be up-to-date since an SMB + client may have modified the file locally. The value of Content-Length may not reflect that + fact until the handle is closed or the op-lock is broken. To retrieve current property values, + call Get File Properties. Required. + :vartype content_length: int + :ivar creation_time: The creation time. + :vartype creation_time: str + :ivar last_access_time: The last access time. + :vartype last_access_time: str + :ivar last_write_time: The last write time. + :vartype last_write_time: str + :ivar change_time: The change time. + :vartype change_time: str + :ivar last_modified: The last modified time. + :vartype last_modified: ~datetime.datetime + :ivar etag: The ETag of the file. + :vartype etag: str + """ + + content_length: int = rest_field( + name="contentLength", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Content-Length", "text": False, "unwrapped": False}, + ) + """Content length of the file. This value may not be up-to-date since an SMB client may have + modified the file locally. The value of Content-Length may not reflect that fact until the + handle is closed or the op-lock is broken. To retrieve current property values, call Get File + Properties. Required.""" + creation_time: Optional[str] = rest_field( + name="creationTime", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "CreationTime", "text": False, "unwrapped": False}, + ) + """The creation time.""" + last_access_time: Optional[str] = rest_field( + name="lastAccessTime", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "LastAccessTime", "text": False, "unwrapped": False}, + ) + """The last access time.""" + last_write_time: Optional[str] = rest_field( + name="lastWriteTime", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "LastWriteTime", "text": False, "unwrapped": False}, + ) + """The last write time.""" + change_time: Optional[str] = rest_field( + name="changeTime", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ChangeTime", "text": False, "unwrapped": False}, + ) + """The change time.""" + last_modified: Optional[datetime.datetime] = rest_field( + name="lastModified", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "Last-Modified", "text": False, "unwrapped": False}, + ) + """The last modified time.""" + etag: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Etag", "text": False, "unwrapped": False}, + ) + """The ETag of the file.""" + + _xml = {"attribute": False, "name": "FileProperty", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + content_length: int, + creation_time: Optional[str] = None, + last_access_time: Optional[str] = None, + last_write_time: Optional[str] = None, + change_time: Optional[str] = None, + last_modified: Optional[datetime.datetime] = None, + etag: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FileRange(_Model): + """An Azure Storage file range. + + :ivar start: Start of the range. Required. + :vartype start: int + :ivar end: End of the range. Required. + :vartype end: int + """ + + start: int = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + ) + """Start of the range. Required.""" + end: int = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "End", "text": False, "unwrapped": False}, + ) + """End of the range. Required.""" + + _xml = {"attribute": False, "name": "Range", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + start: int, + end: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class FilesAndDirectoriesListSegment(_Model): + """Abstract for entries that can be listed from Directory. + + :ivar directory_items: The directory items. Required. + :vartype directory_items: ~azure.storage.fileshare._generated.models.DirectoryItem + :ivar file_items: The file items. Required. + :vartype file_items: ~azure.storage.fileshare._generated.models.FileItem + """ + + directory_items: list["_models.DirectoryItem"] = rest_field( + name="directoryItems", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "Directory", "name": "Directory", "text": False, "unwrapped": True}, + ) + """The directory items. Required.""" + file_items: list["_models.FileItem"] = rest_field( + name="fileItems", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "File", "name": "File", "text": False, "unwrapped": True}, + ) + """The file items. Required.""" + + _xml = {"attribute": False, "name": "FilesAndDirectoriesListSegment", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + directory_items: list["_models.DirectoryItem"], + file_items: list["_models.FileItem"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class HandleItem(_Model): + """A listed Azure Storage handle item. + + :ivar handle_id: XSMB service handle ID. Required. + :vartype handle_id: str + :ivar path: The path. Required. + :vartype path: ~azure.storage.fileshare._generated.models.StringEncoded + :ivar file_id: FileId uniquely identifies the file or directory. Required. + :vartype file_id: str + :ivar parent_id: ParentId uniquely identifies the parent directory of the object. + :vartype parent_id: str + :ivar session_id: SMB session ID in context of which the file handle was opened. Required. + :vartype session_id: str + :ivar client_ip: Client IP that opened the handle. Required. + :vartype client_ip: str + :ivar client_name: Name of the client machine where the share is being mounted. Required. + :vartype client_name: str + :ivar open_time: Time when the session that previously opened the handle has last been + reconnected. (UTC). Required. + :vartype open_time: ~datetime.datetime + :ivar last_reconnect_time: Time handle was last connected to (UTC). + :vartype last_reconnect_time: ~datetime.datetime + :ivar access_right_list: The access rights. + :vartype access_right_list: list[str or ~azure.storage.fileshare.models.AccessRight] + """ + + handle_id: str = rest_field( + name="handleId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "HandleId", "text": False, "unwrapped": False}, + ) + """XSMB service handle ID. Required.""" + path: "_models.StringEncoded" = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Path", "text": False, "unwrapped": False}, + ) + """The path. Required.""" + file_id: str = rest_field( + name="fileId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "FileId", "text": False, "unwrapped": False}, + ) + """FileId uniquely identifies the file or directory. Required.""" + parent_id: Optional[str] = rest_field( + name="parentId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ParentId", "text": False, "unwrapped": False}, + ) + """ParentId uniquely identifies the parent directory of the object.""" + session_id: str = rest_field( + name="sessionId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SessionId", "text": False, "unwrapped": False}, + ) + """SMB session ID in context of which the file handle was opened. Required.""" + client_ip: str = rest_field( + name="clientIp", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ClientIp", "text": False, "unwrapped": False}, + ) + """Client IP that opened the handle. Required.""" + client_name: str = rest_field( + name="clientName", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ClientName", "text": False, "unwrapped": False}, + ) + """Name of the client machine where the share is being mounted. Required.""" + open_time: datetime.datetime = rest_field( + name="openTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "OpenTime", "text": False, "unwrapped": False}, + ) + """Time when the session that previously opened the handle has last been reconnected. (UTC). + Required.""" + last_reconnect_time: Optional[datetime.datetime] = rest_field( + name="lastReconnectTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "LastReconnectTime", "text": False, "unwrapped": False}, + ) + """Time handle was last connected to (UTC).""" + access_right_list: Optional[list[Union[str, "_models.AccessRight"]]] = rest_field( + name="accessRightList", + visibility=["read", "create", "update", "delete", "query"], + xml={ + "attribute": False, + "itemsName": "AccessRight", + "name": "AccessRightList", + "text": False, + "unwrapped": False, + }, + ) + """The access rights.""" + + _xml = {"attribute": False, "name": "Handle", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + handle_id: str, + path: "_models.StringEncoded", + file_id: str, + session_id: str, + client_ip: str, + client_name: str, + open_time: datetime.datetime, + parent_id: Optional[str] = None, + last_reconnect_time: Optional[datetime.datetime] = None, + access_right_list: Optional[list[Union[str, "_models.AccessRight"]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class KeyInfo(_Model): + """Key information. + + :ivar start: The date-time the key is active in ISO 8601 UTC time. + :vartype start: str + :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. + :vartype expiry: str + :ivar delegated_user_tid: The delegated user tenant id in Azure AD. + :vartype delegated_user_tid: str + """ + + start: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + ) + """The date-time the key is active in ISO 8601 UTC time.""" + expiry: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Expiry", "text": False, "unwrapped": False}, + ) + """The date-time the key expires in ISO 8601 UTC time. Required.""" + delegated_user_tid: Optional[str] = rest_field( + name="delegatedUserTid", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "DelegatedUserTid", "text": False, "unwrapped": False}, + ) + """The delegated user tenant id in Azure AD.""" + + _xml = {"attribute": False, "name": "KeyInfo", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + expiry: str, + start: Optional[str] = None, + delegated_user_tid: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListFilesAndDirectoriesSegmentResponse(_Model): + """An enumeration of directories and files. + + :ivar service_endpoint: The service endpoint. Required. + :vartype service_endpoint: str + :ivar share_name: The share name. Required. + :vartype share_name: str + :ivar share_snapshot: The share snapshot. + :vartype share_snapshot: str + :ivar encoded: Whether the listing is encoded. + :vartype encoded: bool + :ivar directory_path: The directory path. Required. + :vartype directory_path: str + :ivar prefix: The prefix. Required. + :vartype prefix: ~azure.storage.fileshare._generated.models.StringEncoded + :ivar marker: The marker. + :vartype marker: str + :ivar max_results: The max results. + :vartype max_results: int + :ivar segment: Abstract for entries that can be listed from Directory. Required. + :vartype segment: ~azure.storage.fileshare._generated.models.FilesAndDirectoriesListSegment + :ivar next_marker: The next marker. Required. + :vartype next_marker: str + :ivar directory_id: The directory ID. + :vartype directory_id: str + """ + + service_endpoint: str = rest_field( + name="serviceEndpoint", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": True, "name": "ServiceEndpoint", "text": False, "unwrapped": False}, + ) + """The service endpoint. Required.""" + share_name: str = rest_field( + name="shareName", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": True, "name": "ShareName", "text": False, "unwrapped": False}, + ) + """The share name. Required.""" + share_snapshot: Optional[str] = rest_field( + name="shareSnapshot", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": True, "name": "ShareSnapshot", "text": False, "unwrapped": False}, + ) + """The share snapshot.""" + encoded: Optional[bool] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": True, "name": "Encoded", "text": False, "unwrapped": False}, + ) + """Whether the listing is encoded.""" + directory_path: str = rest_field( + name="directoryPath", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": True, "name": "DirectoryPath", "text": False, "unwrapped": False}, + ) + """The directory path. Required.""" + prefix: "_models.StringEncoded" = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Prefix", "text": False, "unwrapped": False}, + ) + """The prefix. Required.""" + marker: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Marker", "text": False, "unwrapped": False}, + ) + """The marker.""" + max_results: Optional[int] = rest_field( + name="maxResults", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MaxResults", "text": False, "unwrapped": False}, + ) + """The max results.""" + segment: "_models.FilesAndDirectoriesListSegment" = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Entries", "text": False, "unwrapped": False}, + ) + """Abstract for entries that can be listed from Directory. Required.""" + next_marker: str = rest_field( + name="nextMarker", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "NextMarker", "text": False, "unwrapped": False}, + ) + """The next marker. Required.""" + directory_id: Optional[str] = rest_field( + name="directoryId", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "DirectoryId", "text": False, "unwrapped": False}, + ) + """The directory ID.""" + + _xml = {"attribute": False, "name": "EnumerationResults", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + service_endpoint: str, + share_name: str, + directory_path: str, + prefix: "_models.StringEncoded", + segment: "_models.FilesAndDirectoriesListSegment", + next_marker: str, + share_snapshot: Optional[str] = None, + encoded: Optional[bool] = None, + marker: Optional[str] = None, + max_results: Optional[int] = None, + directory_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListHandlesResponse(_Model): + """An enumeration of handles. + + :ivar handle_list: The handle list. + :vartype handle_list: ~azure.storage.fileshare._generated.models.HandleItem + :ivar next_marker: The next marker. Required. + :vartype next_marker: str + """ + + handle_list: Optional[list["_models.HandleItem"]] = rest_field( + name="handleList", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "Handle", "name": "Entries", "text": False, "unwrapped": False}, + ) + """The handle list.""" + next_marker: str = rest_field( + name="nextMarker", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "NextMarker", "text": False, "unwrapped": False}, + ) + """The next marker. Required.""" + + _xml = {"attribute": False, "name": "EnumerationResults", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + next_marker: str, + handle_list: Optional[list["_models.HandleItem"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ListSharesResponse(_Model): + """An enumeration of shares. + + :ivar service_endpoint: The service endpoint. Required. + :vartype service_endpoint: str + :ivar prefix: The prefix. + :vartype prefix: str + :ivar marker: The marker. + :vartype marker: str + :ivar max_results: The max results. + :vartype max_results: int + :ivar share_items: The share items. + :vartype share_items: ~azure.storage.fileshare._generated.models.ShareItemInternal + :ivar next_marker: The next marker. Required. + :vartype next_marker: str + """ + + service_endpoint: str = rest_field( + name="serviceEndpoint", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": True, "name": "ServiceEndpoint", "text": False, "unwrapped": False}, + ) + """The service endpoint. Required.""" + prefix: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Prefix", "text": False, "unwrapped": False}, + ) + """The prefix.""" + marker: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Marker", "text": False, "unwrapped": False}, + ) + """The marker.""" + max_results: Optional[int] = rest_field( + name="maxResults", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MaxResults", "text": False, "unwrapped": False}, + ) + """The max results.""" + share_items: Optional[list["_models.ShareItemInternal"]] = rest_field( + name="shareItems", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "Share", "name": "Shares", "text": False, "unwrapped": False}, + ) + """The share items.""" + next_marker: str = rest_field( + name="nextMarker", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "NextMarker", "text": False, "unwrapped": False}, + ) + """The next marker. Required.""" + + _xml = {"attribute": False, "name": "EnumerationResults", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + service_endpoint: str, + next_marker: str, + prefix: Optional[str] = None, + marker: Optional[str] = None, + max_results: Optional[int] = None, + share_items: Optional[list["_models.ShareItemInternal"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class Metrics(_Model): + """Storage Analytics metrics for file service. + + :ivar version: The version of Storage Analytics to configure. Required. + :vartype version: str + :ivar enabled: Indicates whether metrics are enabled for the File service. Required. + :vartype enabled: bool + :ivar include_apis: Indicates whether metrics should generate summary statistics for called API + operations. + :vartype include_apis: bool + :ivar retention_policy: The retention policy. + :vartype retention_policy: ~azure.storage.fileshare._generated.models.RetentionPolicy + """ + + version: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + ) + """The version of Storage Analytics to configure. Required.""" + enabled: bool = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + ) + """Indicates whether metrics are enabled for the File service. Required.""" + include_apis: Optional[bool] = rest_field( + name="includeApis", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "IncludeAPIs", "text": False, "unwrapped": False}, + ) + """Indicates whether metrics should generate summary statistics for called API operations.""" + retention_policy: Optional["_models.RetentionPolicy"] = rest_field( + name="retentionPolicy", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "RetentionPolicy", "text": False, "unwrapped": False}, + ) + """The retention policy.""" + + _xml = {"attribute": False, "name": "Metrics", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + version: str, + enabled: bool, + include_apis: Optional[bool] = None, + retention_policy: Optional["_models.RetentionPolicy"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class RetentionPolicy(_Model): + """The retention policy. + + :ivar enabled: Indicates whether a retention policy is enabled for the File service. If false, + metrics data is retained, and the user is responsible for deleting it. Required. + :vartype enabled: bool + :ivar days: Indicates the number of days that metrics data should be retained. All data older + than this value will be deleted. Metrics data is deleted on a best-effort basis after the + retention period expires. + :vartype days: int + """ + + enabled: bool = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + ) + """Indicates whether a retention policy is enabled for the File service. If false, metrics data is + retained, and the user is responsible for deleting it. Required.""" + days: Optional[int] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Days", "text": False, "unwrapped": False}, + ) + """Indicates the number of days that metrics data should be retained. All data older than this + value will be deleted. Metrics data is deleted on a best-effort basis after the retention + period expires.""" + + _xml = {"attribute": False, "name": "RetentionPolicy", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + enabled: bool, + days: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShareFileRangeList(_Model): + """The list of file ranges. + + :ivar ranges: The file ranges. + :vartype ranges: ~azure.storage.fileshare._generated.models.FileRange + :ivar clear_ranges: The clear ranges. + :vartype clear_ranges: ~azure.storage.fileshare._generated.models.ClearRange + """ + + ranges: Optional[list["_models.FileRange"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "Range", "name": "Range", "text": False, "unwrapped": True}, + ) + """The file ranges.""" + clear_ranges: Optional[list["_models.ClearRange"]] = rest_field( + name="clearRanges", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "ClearRange", "name": "ClearRange", "text": False, "unwrapped": True}, + ) + """The clear ranges.""" + + _xml = {"attribute": False, "name": "Ranges", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + ranges: Optional[list["_models.FileRange"]] = None, + clear_ranges: Optional[list["_models.ClearRange"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShareItemInternal(_Model): + """A listed Azure Storage share item. + + :ivar name: The share name. Required. + :vartype name: str + :ivar snapshot: The share snapshot. + :vartype snapshot: str + :ivar deleted: Whether the share is deleted. + :vartype deleted: bool + :ivar version: The share version. + :vartype version: str + :ivar properties: Properties of a share. Required. + :vartype properties: ~azure.storage.fileshare._generated.models.SharePropertiesInternal + :ivar metadata: Dictionary of . + :vartype metadata: dict[str, str] + """ + + name: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Name", "text": False, "unwrapped": False}, + ) + """The share name. Required.""" + snapshot: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Snapshot", "text": False, "unwrapped": False}, + ) + """The share snapshot.""" + deleted: Optional[bool] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Deleted", "text": False, "unwrapped": False}, + ) + """Whether the share is deleted.""" + version: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + ) + """The share version.""" + properties: "_models.SharePropertiesInternal" = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Properties", "text": False, "unwrapped": False}, + ) + """Properties of a share. Required.""" + metadata: Optional[dict[str, str]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Metadata", "text": False, "unwrapped": False}, + ) + """Dictionary of .""" + + _xml = {"attribute": False, "name": "Share", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + name: str, + properties: "_models.SharePropertiesInternal", + snapshot: Optional[str] = None, + deleted: Optional[bool] = None, + version: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShareNfsSettings(_Model): + """Settings for SMB protocol. + + :ivar encryption_in_transit: Enable or disable encryption in transit. + :vartype encryption_in_transit: + ~azure.storage.fileshare._generated.models.ShareNfsSettingsEncryptionInTransit + """ + + encryption_in_transit: Optional["_models.ShareNfsSettingsEncryptionInTransit"] = rest_field( + name="encryptionInTransit", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "EncryptionInTransit", "text": False, "unwrapped": False}, + ) + """Enable or disable encryption in transit.""" + + _xml = {"attribute": False, "name": "NFS", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + encryption_in_transit: Optional["_models.ShareNfsSettingsEncryptionInTransit"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShareNfsSettingsEncryptionInTransit(_Model): + """Enable or disable encryption in transit. + + :ivar required: If encryption in transit is required. + :vartype required: bool + """ + + required: Optional[bool] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Required", "text": False, "unwrapped": False}, + ) + """If encryption in transit is required.""" + + _xml = {"attribute": False, "name": "ShareNfsSettingsEncryptionInTransit", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + required: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SharePermission(_Model): + """A permission (a security descriptor) at the share level. + + :ivar permission: The permission in the Security Descriptor Definition Language (SDDL). + Required. + :vartype permission: str + :ivar format: The permission format. Known values are: "Sddl" and "Binary". + :vartype format: str or ~azure.storage.fileshare.models.FilePermissionFormat + """ + + permission: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The permission in the Security Descriptor Definition Language (SDDL). Required.""" + format: Optional[Union[str, "_models.FilePermissionFormat"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The permission format. Known values are: \"Sddl\" and \"Binary\".""" + + @overload + def __init__( + self, + *, + permission: str, + format: Optional[Union[str, "_models.FilePermissionFormat"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SharePropertiesInternal(_Model): + """Properties of a share. + + :ivar last_modified: The last modified time. Required. + :vartype last_modified: ~datetime.datetime + :ivar etag: The ETag of the share. Required. + :vartype etag: str + :ivar quota: The share quota. Required. + :vartype quota: int + :ivar provisioned_iops: The provisioned IOPS. + :vartype provisioned_iops: int + :ivar provisioned_ingress_m_bps: The provisioned ingress in MBps. + :vartype provisioned_ingress_m_bps: int + :ivar provisioned_egress_m_bps: The provisioned egress in MBps. + :vartype provisioned_egress_m_bps: int + :ivar provisioned_bandwidth_mi_bps: The provisioned bandwidth in MiBps. + :vartype provisioned_bandwidth_mi_bps: int + :ivar next_allowed_quota_downgrade_time: The next allowed quota downgrade time. + :vartype next_allowed_quota_downgrade_time: ~datetime.datetime + :ivar deleted_time: The deleted time. + :vartype deleted_time: ~datetime.datetime + :ivar remaining_retention_days: The remaining retention days. + :vartype remaining_retention_days: int + :ivar access_tier: The access tier. + :vartype access_tier: str + :ivar access_tier_change_time: The access tier change time. + :vartype access_tier_change_time: ~datetime.datetime + :ivar access_tier_transition_state: The access tier transition state. + :vartype access_tier_transition_state: str + :ivar lease_status: The current lease status of the share. Known values are: "locked" and + "unlocked". + :vartype lease_status: str or ~azure.storage.fileshare.models.LeaseStatusType + :ivar lease_state: Lease state of the share. Known values are: "available", "leased", + "expired", "breaking", and "broken". + :vartype lease_state: str or ~azure.storage.fileshare.models.LeaseStateType + :ivar lease_duration: When a share is leased, specifies whether the lease is of infinite or + fixed duration. Known values are: "infinite" and "fixed". + :vartype lease_duration: str or ~azure.storage.fileshare.models.LeaseDurationType + :ivar enabled_protocols: The enabled protocols. + :vartype enabled_protocols: str + :ivar root_squash: The root squash setting. Known values are: "NoRootSquash", "RootSquash", and + "AllSquash". + :vartype root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash + :ivar enable_snapshot_virtual_directory_access: Whether snapshot virtual directory access is + enabled. + :vartype enable_snapshot_virtual_directory_access: bool + :ivar paid_bursting_enabled: Whether paid bursting is enabled. + :vartype paid_bursting_enabled: bool + :ivar paid_bursting_max_iops: The maximum IOPS for paid bursting. + :vartype paid_bursting_max_iops: int + :ivar paid_bursting_max_bandwidth_mibps: The maximum bandwidth for paid bursting in MiBps. + :vartype paid_bursting_max_bandwidth_mibps: int + :ivar included_burst_iops: The included burst IOPS. + :vartype included_burst_iops: int + :ivar max_burst_credits_for_iops: The maximum burst credits for IOPS. + :vartype max_burst_credits_for_iops: int + :ivar next_allowed_provisioned_iops_downgrade_time: The next allowed provisioned IOPS downgrade + time. + :vartype next_allowed_provisioned_iops_downgrade_time: ~datetime.datetime + :ivar next_allowed_provisioned_bandwidth_downgrade_time: The next allowed provisioned bandwidth + downgrade time. + :vartype next_allowed_provisioned_bandwidth_downgrade_time: ~datetime.datetime + :ivar enable_smb_directory_lease: Whether SMB directory lease is enabled. + :vartype enable_smb_directory_lease: bool + """ + + last_modified: datetime.datetime = rest_field( + name="lastModified", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "Last-Modified", "text": False, "unwrapped": False}, + ) + """The last modified time. Required.""" + etag: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Etag", "text": False, "unwrapped": False}, + ) + """The ETag of the share. Required.""" + quota: int = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Quota", "text": False, "unwrapped": False}, + ) + """The share quota. Required.""" + provisioned_iops: Optional[int] = rest_field( + name="provisionedIops", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ProvisionedIops", "text": False, "unwrapped": False}, + ) + """The provisioned IOPS.""" + provisioned_ingress_m_bps: Optional[int] = rest_field( + name="provisionedIngressMBps", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ProvisionedIngressMBps", "text": False, "unwrapped": False}, + ) + """The provisioned ingress in MBps.""" + provisioned_egress_m_bps: Optional[int] = rest_field( + name="provisionedEgressMBps", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ProvisionedEgressMBps", "text": False, "unwrapped": False}, + ) + """The provisioned egress in MBps.""" + provisioned_bandwidth_mi_bps: Optional[int] = rest_field( + name="provisionedBandwidthMiBps", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ProvisionedBandwidthMiBps", "text": False, "unwrapped": False}, + ) + """The provisioned bandwidth in MiBps.""" + next_allowed_quota_downgrade_time: Optional[datetime.datetime] = rest_field( + name="nextAllowedQuotaDowngradeTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "NextAllowedQuotaDowngradeTime", "text": False, "unwrapped": False}, + ) + """The next allowed quota downgrade time.""" + deleted_time: Optional[datetime.datetime] = rest_field( + name="deletedTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "DeletedTime", "text": False, "unwrapped": False}, + ) + """The deleted time.""" + remaining_retention_days: Optional[int] = rest_field( + name="remainingRetentionDays", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "RemainingRetentionDays", "text": False, "unwrapped": False}, + ) + """The remaining retention days.""" + access_tier: Optional[str] = rest_field( + name="accessTier", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AccessTier", "text": False, "unwrapped": False}, + ) + """The access tier.""" + access_tier_change_time: Optional[datetime.datetime] = rest_field( + name="accessTierChangeTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "AccessTierChangeTime", "text": False, "unwrapped": False}, + ) + """The access tier change time.""" + access_tier_transition_state: Optional[str] = rest_field( + name="accessTierTransitionState", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AccessTierTransitionState", "text": False, "unwrapped": False}, + ) + """The access tier transition state.""" + lease_status: Optional[Union[str, "_models.LeaseStatusType"]] = rest_field( + name="leaseStatus", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "LeaseStatus", "text": False, "unwrapped": False}, + ) + """The current lease status of the share. Known values are: \"locked\" and \"unlocked\".""" + lease_state: Optional[Union[str, "_models.LeaseStateType"]] = rest_field( + name="leaseState", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "LeaseState", "text": False, "unwrapped": False}, + ) + """Lease state of the share. Known values are: \"available\", \"leased\", \"expired\", + \"breaking\", and \"broken\".""" + lease_duration: Optional[Union[str, "_models.LeaseDurationType"]] = rest_field( + name="leaseDuration", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "LeaseDuration", "text": False, "unwrapped": False}, + ) + """When a share is leased, specifies whether the lease is of infinite or fixed duration. Known + values are: \"infinite\" and \"fixed\".""" + enabled_protocols: Optional[str] = rest_field( + name="enabledProtocols", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "EnabledProtocols", "text": False, "unwrapped": False}, + ) + """The enabled protocols.""" + root_squash: Optional[Union[str, "_models.ShareRootSquash"]] = rest_field( + name="rootSquash", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "RootSquash", "text": False, "unwrapped": False}, + ) + """The root squash setting. Known values are: \"NoRootSquash\", \"RootSquash\", and \"AllSquash\".""" + enable_snapshot_virtual_directory_access: Optional[bool] = rest_field( + name="enableSnapshotVirtualDirectoryAccess", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "EnableSnapshotVirtualDirectoryAccess", "text": False, "unwrapped": False}, + ) + """Whether snapshot virtual directory access is enabled.""" + paid_bursting_enabled: Optional[bool] = rest_field( + name="paidBurstingEnabled", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "PaidBurstingEnabled", "text": False, "unwrapped": False}, + ) + """Whether paid bursting is enabled.""" + paid_bursting_max_iops: Optional[int] = rest_field( + name="paidBurstingMaxIops", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "PaidBurstingMaxIops", "text": False, "unwrapped": False}, + ) + """The maximum IOPS for paid bursting.""" + paid_bursting_max_bandwidth_mibps: Optional[int] = rest_field( + name="paidBurstingMaxBandwidthMibps", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "PaidBurstingMaxBandwidthMibps", "text": False, "unwrapped": False}, + ) + """The maximum bandwidth for paid bursting in MiBps.""" + included_burst_iops: Optional[int] = rest_field( + name="includedBurstIops", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "IncludedBurstIops", "text": False, "unwrapped": False}, + ) + """The included burst IOPS.""" + max_burst_credits_for_iops: Optional[int] = rest_field( + name="maxBurstCreditsForIops", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MaxBurstCreditsForIops", "text": False, "unwrapped": False}, + ) + """The maximum burst credits for IOPS.""" + next_allowed_provisioned_iops_downgrade_time: Optional[datetime.datetime] = rest_field( + name="nextAllowedProvisionedIopsDowngradeTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={"attribute": False, "name": "NextAllowedProvisionedIopsDowngradeTime", "text": False, "unwrapped": False}, + ) + """The next allowed provisioned IOPS downgrade time.""" + next_allowed_provisioned_bandwidth_downgrade_time: Optional[datetime.datetime] = rest_field( + name="nextAllowedProvisionedBandwidthDowngradeTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc7231", + xml={ + "attribute": False, + "name": "NextAllowedProvisionedBandwidthDowngradeTime", + "text": False, + "unwrapped": False, + }, + ) + """The next allowed provisioned bandwidth downgrade time.""" + enable_smb_directory_lease: Optional[bool] = rest_field( + name="enableSmbDirectoryLease", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "EnableSmbDirectoryLease", "text": False, "unwrapped": False}, + ) + """Whether SMB directory lease is enabled.""" + + _xml = {"attribute": False, "name": "SharePropertiesInternal", "text": False, "unwrapped": False} + + @overload + def __init__( # pylint: disable=too-many-locals + self, + *, + last_modified: datetime.datetime, + etag: str, + quota: int, + provisioned_iops: Optional[int] = None, + provisioned_ingress_m_bps: Optional[int] = None, + provisioned_egress_m_bps: Optional[int] = None, + provisioned_bandwidth_mi_bps: Optional[int] = None, + next_allowed_quota_downgrade_time: Optional[datetime.datetime] = None, + deleted_time: Optional[datetime.datetime] = None, + remaining_retention_days: Optional[int] = None, + access_tier: Optional[str] = None, + access_tier_change_time: Optional[datetime.datetime] = None, + access_tier_transition_state: Optional[str] = None, + lease_status: Optional[Union[str, "_models.LeaseStatusType"]] = None, + lease_state: Optional[Union[str, "_models.LeaseStateType"]] = None, + lease_duration: Optional[Union[str, "_models.LeaseDurationType"]] = None, + enabled_protocols: Optional[str] = None, + root_squash: Optional[Union[str, "_models.ShareRootSquash"]] = None, + enable_snapshot_virtual_directory_access: Optional[bool] = None, + paid_bursting_enabled: Optional[bool] = None, + paid_bursting_max_iops: Optional[int] = None, + paid_bursting_max_bandwidth_mibps: Optional[int] = None, + included_burst_iops: Optional[int] = None, + max_burst_credits_for_iops: Optional[int] = None, + next_allowed_provisioned_iops_downgrade_time: Optional[datetime.datetime] = None, + next_allowed_provisioned_bandwidth_downgrade_time: Optional[datetime.datetime] = None, + enable_smb_directory_lease: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShareProtocolSettings(_Model): + """Protocol settings. + + :ivar smb: Settings for SMB protocol. + :vartype smb: ~azure.storage.fileshare._generated.models.ShareSmbSettings + :ivar nfs: Settings for NFS protocol. + :vartype nfs: ~azure.storage.fileshare._generated.models.ShareNfsSettings + """ + + smb: Optional["_models.ShareSmbSettings"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SMB", "text": False, "unwrapped": False}, + ) + """Settings for SMB protocol.""" + nfs: Optional["_models.ShareNfsSettings"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "NFS", "text": False, "unwrapped": False}, + ) + """Settings for NFS protocol.""" + + _xml = {"attribute": False, "name": "ProtocolSettings", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + smb: Optional["_models.ShareSmbSettings"] = None, + nfs: Optional["_models.ShareNfsSettings"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShareSmbSettings(_Model): + """Settings for SMB protocol. + + :ivar multichannel: Settings for SMB Multichannel. + :vartype multichannel: ~azure.storage.fileshare._generated.models.SmbMultichannel + :ivar encryption_in_transit: Enable or disable encryption in transit. + :vartype encryption_in_transit: + ~azure.storage.fileshare._generated.models.ShareSmbSettingsEncryptionInTransit + """ + + multichannel: Optional["_models.SmbMultichannel"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Multichannel", "text": False, "unwrapped": False}, + ) + """Settings for SMB Multichannel.""" + encryption_in_transit: Optional["_models.ShareSmbSettingsEncryptionInTransit"] = rest_field( + name="encryptionInTransit", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "EncryptionInTransit", "text": False, "unwrapped": False}, + ) + """Enable or disable encryption in transit.""" + + _xml = {"attribute": False, "name": "SMB", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + multichannel: Optional["_models.SmbMultichannel"] = None, + encryption_in_transit: Optional["_models.ShareSmbSettingsEncryptionInTransit"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShareSmbSettingsEncryptionInTransit(_Model): + """Enable or disable encryption in transit. + + :ivar required: If encryption in transit is required. + :vartype required: bool + """ + + required: Optional[bool] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Required", "text": False, "unwrapped": False}, + ) + """If encryption in transit is required.""" + + _xml = {"attribute": False, "name": "ShareSmbSettingsEncryptionInTransit", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + required: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ShareStats(_Model): + """Stats for the share. + + :ivar share_usage_bytes: The approximate size of the data stored in bytes. Note that this value + may not include all recently created or recently resized files. Required. + :vartype share_usage_bytes: int + """ + + share_usage_bytes: int = rest_field( + name="shareUsageBytes", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ShareUsageBytes", "text": False, "unwrapped": False}, + ) + """The approximate size of the data stored in bytes. Note that this value may not include all + recently created or recently resized files. Required.""" + + _xml = {"attribute": False, "name": "ShareStats", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + share_usage_bytes: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SignedIdentifier(_Model): + """Signed identifier. + + :ivar id: A unique id. Required. + :vartype id: str + :ivar access_policy: The access policy. + :vartype access_policy: ~azure.storage.fileshare._generated.models.AccessPolicy + """ + + id: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Id", "text": False, "unwrapped": False}, + ) + """A unique id. Required.""" + access_policy: Optional["_models.AccessPolicy"] = rest_field( + name="accessPolicy", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "AccessPolicy", "text": False, "unwrapped": False}, + ) + """The access policy.""" + + _xml = {"attribute": False, "name": "SignedIdentifier", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + access_policy: Optional["_models.AccessPolicy"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SignedIdentifiers(_Model): + """Represents an array of signed identifiers. + + :ivar items_property: The array of signed identifiers. Required. + :vartype items_property: ~azure.storage.fileshare._generated.models.SignedIdentifier + """ + + items_property: list["_models.SignedIdentifier"] = rest_field( + name="items", + visibility=["read", "create", "update", "delete", "query"], + xml={ + "attribute": False, + "itemsName": "SignedIdentifier", + "name": "SignedIdentifier", + "text": False, + "unwrapped": True, + }, + original_tsp_name="items", + ) + """The array of signed identifiers. Required.""" + + _xml = {"attribute": False, "name": "SignedIdentifiers", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + items_property: list["_models.SignedIdentifier"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class SmbMultichannel(_Model): + """Settings for SMB multichannel. + + :ivar enabled: If SMB multichannel is enabled. + :vartype enabled: bool + """ + + enabled: Optional[bool] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + ) + """If SMB multichannel is enabled.""" + + _xml = {"attribute": False, "name": "Multichannel", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + enabled: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StorageServiceProperties(_Model): + """Storage service properties. + + :ivar hour_metrics: A summary of request statistics grouped by API in hourly aggregates for + files. + :vartype hour_metrics: ~azure.storage.fileshare._generated.models.Metrics + :ivar minute_metrics: A summary of request statistics grouped by API in minute aggregates for + files. + :vartype minute_metrics: ~azure.storage.fileshare._generated.models.Metrics + :ivar protocol: Protocol settings. + :vartype protocol: ~azure.storage.fileshare._generated.models.ShareProtocolSettings + :ivar cors: The set of CORS rules. + :vartype cors: ~azure.storage.fileshare._generated.models.CorsRule + """ + + hour_metrics: Optional["_models.Metrics"] = rest_field( + name="hourMetrics", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "HourMetrics", "text": False, "unwrapped": False}, + ) + """A summary of request statistics grouped by API in hourly aggregates for files.""" + minute_metrics: Optional["_models.Metrics"] = rest_field( + name="minuteMetrics", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "MinuteMetrics", "text": False, "unwrapped": False}, + ) + """A summary of request statistics grouped by API in minute aggregates for files.""" + protocol: Optional["_models.ShareProtocolSettings"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ProtocolSettings", "text": False, "unwrapped": False}, + ) + """Protocol settings.""" + cors: Optional[list["_models.CorsRule"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "itemsName": "CorsRule", "name": "Cors", "text": False, "unwrapped": False}, + ) + """The set of CORS rules.""" + + _xml = {"attribute": False, "name": "StorageServiceProperties", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + hour_metrics: Optional["_models.Metrics"] = None, + minute_metrics: Optional["_models.Metrics"] = None, + protocol: Optional["_models.ShareProtocolSettings"] = None, + cors: Optional[list["_models.CorsRule"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class StringEncoded(_Model): + """An encoded string value. + + :ivar encoded: Whether the value is encoded. + :vartype encoded: bool + :ivar content: The string content. + :vartype content: str + """ + + encoded: Optional[bool] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": True, "name": "Encoded", "text": False, "unwrapped": False}, + ) + """Whether the value is encoded.""" + content: Optional[str] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "content", "text": True, "unwrapped": False}, + ) + """The string content.""" + + _xml = {"attribute": False, "name": "StringEncoded", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + encoded: Optional[bool] = None, + content: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class UserDelegationKey(_Model): + """A user delegation key. + + :ivar signed_oid: The Azure Active Directory object ID in GUID format. Required. + :vartype signed_oid: str + :ivar signed_tid: The Azure Active Directory tenant ID in GUID format. Required. + :vartype signed_tid: str + :ivar signed_start: The date-time the key is active. Required. + :vartype signed_start: str + :ivar signed_expiry: The date-time the key expires. Required. + :vartype signed_expiry: str + :ivar signed_service: Abbreviation of the Azure Storage service that accepts the key. Required. + :vartype signed_service: str + :ivar signed_version: The service version that created the key. Required. + :vartype signed_version: str + :ivar signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if + DelegatedUserTid is specified. + :vartype signed_delegated_user_tid: str + :ivar value: The key as a base64 string. Required. + :vartype value: str + """ + + signed_oid: str = rest_field( + name="signedOid", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedOid", "text": False, "unwrapped": False}, + ) + """The Azure Active Directory object ID in GUID format. Required.""" + signed_tid: str = rest_field( + name="signedTid", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedTid", "text": False, "unwrapped": False}, + ) + """The Azure Active Directory tenant ID in GUID format. Required.""" + signed_start: str = rest_field( + name="signedStart", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedStart", "text": False, "unwrapped": False}, + ) + """The date-time the key is active. Required.""" + signed_expiry: str = rest_field( + name="signedExpiry", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedExpiry", "text": False, "unwrapped": False}, + ) + """The date-time the key expires. Required.""" + signed_service: str = rest_field( + name="signedService", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedService", "text": False, "unwrapped": False}, + ) + """Abbreviation of the Azure Storage service that accepts the key. Required.""" + signed_version: str = rest_field( + name="signedVersion", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedVersion", "text": False, "unwrapped": False}, + ) + """The service version that created the key. Required.""" + signed_delegated_user_tid: Optional[str] = rest_field( + name="signedDelegatedUserTid", + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "SignedDelegatedUserTid", "text": False, "unwrapped": False}, + ) + """The delegated user tenant id in Azure AD. Return if DelegatedUserTid is specified.""" + value: str = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "Value", "text": False, "unwrapped": False}, + ) + """The key as a base64 string. Required.""" + + _xml = {"attribute": False, "name": "UserDelegationKey", "text": False, "unwrapped": False} + + @overload + def __init__( + self, + *, + signed_oid: str, + signed_tid: str, + signed_start: str, + signed_expiry: str, + signed_service: str, + signed_version: str, + value: str, + signed_delegated_user_tid: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models_py3.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models_py3.py deleted file mode 100644 index 14572ebc405a..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models_py3.py +++ /dev/null @@ -1,1963 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import datetime -from typing import Any, Optional, TYPE_CHECKING, Union - -from .._utils import serialization as _serialization - -if TYPE_CHECKING: - from .. import models as _models - - -class AccessPolicy(_serialization.Model): - """An Access policy. - - :ivar start: The date-time the policy is active. - :vartype start: str - :ivar expiry: The date-time the policy expires. - :vartype expiry: str - :ivar permission: The permissions for the ACL policy. - :vartype permission: str - """ - - _attribute_map = { - "start": {"key": "Start", "type": "str"}, - "expiry": {"key": "Expiry", "type": "str"}, - "permission": {"key": "Permission", "type": "str"}, - } - - def __init__( - self, - *, - start: Optional[str] = None, - expiry: Optional[str] = None, - permission: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword start: The date-time the policy is active. - :paramtype start: str - :keyword expiry: The date-time the policy expires. - :paramtype expiry: str - :keyword permission: The permissions for the ACL policy. - :paramtype permission: str - """ - super().__init__(**kwargs) - self.start = start - self.expiry = expiry - self.permission = permission - - -class ClearRange(_serialization.Model): - """ClearRange. - - All required parameters must be populated in order to send to server. - - :ivar start: Required. - :vartype start: int - :ivar end: Required. - :vartype end: int - """ - - _validation = { - "start": {"required": True}, - "end": {"required": True}, - } - - _attribute_map = { - "start": {"key": "Start", "type": "int", "xml": {"name": "Start"}}, - "end": {"key": "End", "type": "int", "xml": {"name": "End"}}, - } - _xml_map = {"name": "ClearRange"} - - def __init__(self, *, start: int, end: int, **kwargs: Any) -> None: - """ - :keyword start: Required. - :paramtype start: int - :keyword end: Required. - :paramtype end: int - """ - super().__init__(**kwargs) - self.start = start - self.end = end - - -class CopyFileSmbInfo(_serialization.Model): - """Parameter group. - - :ivar file_attributes: Specifies either the option to copy file attributes from a source - file(source) to a target file or a list of attributes to set on a target file. - :vartype file_attributes: str - :ivar file_creation_time: Specifies either the option to copy file creation time from a source - file(source) to a target file or a time value in ISO 8601 format to set as creation time on a - target file. - :vartype file_creation_time: str - :ivar file_last_write_time: Specifies either the option to copy file last write time from a - source file(source) to a target file or a time value in ISO 8601 format to set as last write - time on a target file. - :vartype file_last_write_time: str - :ivar file_change_time: Specifies either the option to copy file last write time from a source - file(source) to a target file or a time value in ISO 8601 format to set as last write time on a - target file. - :vartype file_change_time: str - :ivar file_permission_copy_mode: Specifies the option to copy file security descriptor from - source file or to set it using the value which is defined by the header value of - x-ms-file-permission or x-ms-file-permission-key. Known values are: "source" and "override". - :vartype file_permission_copy_mode: str or - ~azure.storage.fileshare.models.PermissionCopyModeType - :ivar ignore_read_only: Specifies the option to overwrite the target file if it already exists - and has read-only attribute set. - :vartype ignore_read_only: bool - :ivar set_archive_attribute: Specifies the option to set archive attribute on a target file. - True means archive attribute will be set on a target file despite attribute overrides or a - source file state. - :vartype set_archive_attribute: bool - """ - - _attribute_map = { - "file_attributes": {"key": "fileAttributes", "type": "str"}, - "file_creation_time": {"key": "fileCreationTime", "type": "str"}, - "file_last_write_time": {"key": "fileLastWriteTime", "type": "str"}, - "file_change_time": {"key": "fileChangeTime", "type": "str"}, - "file_permission_copy_mode": {"key": "filePermissionCopyMode", "type": "str"}, - "ignore_read_only": {"key": "ignoreReadOnly", "type": "bool"}, - "set_archive_attribute": {"key": "setArchiveAttribute", "type": "bool"}, - } - - def __init__( - self, - *, - file_attributes: Optional[str] = None, - file_creation_time: Optional[str] = None, - file_last_write_time: Optional[str] = None, - file_change_time: Optional[str] = None, - file_permission_copy_mode: Optional[Union[str, "_models.PermissionCopyModeType"]] = None, - ignore_read_only: Optional[bool] = None, - set_archive_attribute: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword file_attributes: Specifies either the option to copy file attributes from a source - file(source) to a target file or a list of attributes to set on a target file. - :paramtype file_attributes: str - :keyword file_creation_time: Specifies either the option to copy file creation time from a - source file(source) to a target file or a time value in ISO 8601 format to set as creation time - on a target file. - :paramtype file_creation_time: str - :keyword file_last_write_time: Specifies either the option to copy file last write time from a - source file(source) to a target file or a time value in ISO 8601 format to set as last write - time on a target file. - :paramtype file_last_write_time: str - :keyword file_change_time: Specifies either the option to copy file last write time from a - source file(source) to a target file or a time value in ISO 8601 format to set as last write - time on a target file. - :paramtype file_change_time: str - :keyword file_permission_copy_mode: Specifies the option to copy file security descriptor from - source file or to set it using the value which is defined by the header value of - x-ms-file-permission or x-ms-file-permission-key. Known values are: "source" and "override". - :paramtype file_permission_copy_mode: str or - ~azure.storage.fileshare.models.PermissionCopyModeType - :keyword ignore_read_only: Specifies the option to overwrite the target file if it already - exists and has read-only attribute set. - :paramtype ignore_read_only: bool - :keyword set_archive_attribute: Specifies the option to set archive attribute on a target file. - True means archive attribute will be set on a target file despite attribute overrides or a - source file state. - :paramtype set_archive_attribute: bool - """ - super().__init__(**kwargs) - self.file_attributes = file_attributes - self.file_creation_time = file_creation_time - self.file_last_write_time = file_last_write_time - self.file_change_time = file_change_time - self.file_permission_copy_mode = file_permission_copy_mode - self.ignore_read_only = ignore_read_only - self.set_archive_attribute = set_archive_attribute - - -class CorsRule(_serialization.Model): - """CORS is an HTTP feature that enables a web application running under one domain to access - resources in another domain. Web browsers implement a security restriction known as same-origin - policy that prevents a web page from calling APIs in a different domain; CORS provides a secure - way to allow one domain (the origin domain) to call APIs in another domain. - - All required parameters must be populated in order to send to server. - - :ivar allowed_origins: The origin domains that are permitted to make a request against the - storage service via CORS. The origin domain is the domain from which the request originates. - Note that the origin must be an exact case-sensitive match with the origin that the user age - sends to the service. You can also use the wildcard character '*' to allow all origin domains - to make requests via CORS. Required. - :vartype allowed_origins: str - :ivar allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a - CORS request. (comma separated). Required. - :vartype allowed_methods: str - :ivar allowed_headers: The request headers that the origin domain may specify on the CORS - request. Required. - :vartype allowed_headers: str - :ivar exposed_headers: The response headers that may be sent in the response to the CORS - request and exposed by the browser to the request issuer. Required. - :vartype exposed_headers: str - :ivar max_age_in_seconds: The maximum amount time that a browser should cache the preflight - OPTIONS request. Required. - :vartype max_age_in_seconds: int - """ - - _validation = { - "allowed_origins": {"required": True}, - "allowed_methods": {"required": True}, - "allowed_headers": {"required": True}, - "exposed_headers": {"required": True}, - "max_age_in_seconds": {"required": True, "minimum": 0}, - } - - _attribute_map = { - "allowed_origins": {"key": "AllowedOrigins", "type": "str"}, - "allowed_methods": {"key": "AllowedMethods", "type": "str"}, - "allowed_headers": {"key": "AllowedHeaders", "type": "str"}, - "exposed_headers": {"key": "ExposedHeaders", "type": "str"}, - "max_age_in_seconds": {"key": "MaxAgeInSeconds", "type": "int"}, - } - - def __init__( - self, - *, - allowed_origins: str, - allowed_methods: str, - allowed_headers: str, - exposed_headers: str, - max_age_in_seconds: int, - **kwargs: Any - ) -> None: - """ - :keyword allowed_origins: The origin domains that are permitted to make a request against the - storage service via CORS. The origin domain is the domain from which the request originates. - Note that the origin must be an exact case-sensitive match with the origin that the user age - sends to the service. You can also use the wildcard character '*' to allow all origin domains - to make requests via CORS. Required. - :paramtype allowed_origins: str - :keyword allowed_methods: The methods (HTTP request verbs) that the origin domain may use for a - CORS request. (comma separated). Required. - :paramtype allowed_methods: str - :keyword allowed_headers: The request headers that the origin domain may specify on the CORS - request. Required. - :paramtype allowed_headers: str - :keyword exposed_headers: The response headers that may be sent in the response to the CORS - request and exposed by the browser to the request issuer. Required. - :paramtype exposed_headers: str - :keyword max_age_in_seconds: The maximum amount time that a browser should cache the preflight - OPTIONS request. Required. - :paramtype max_age_in_seconds: int - """ - super().__init__(**kwargs) - self.allowed_origins = allowed_origins - self.allowed_methods = allowed_methods - self.allowed_headers = allowed_headers - self.exposed_headers = exposed_headers - self.max_age_in_seconds = max_age_in_seconds - - -class DestinationLeaseAccessConditions(_serialization.Model): - """Parameter group. - - :ivar destination_lease_id: Required if the destination file has an active infinite lease. The - lease ID specified for this header must match the lease ID of the destination file. If the - request does not include the lease ID or it is not valid, the operation fails with status code - 412 (Precondition Failed). If this header is specified and the destination file does not - currently have an active lease, the operation will also fail with status code 412 (Precondition - Failed). - :vartype destination_lease_id: str - """ - - _attribute_map = { - "destination_lease_id": {"key": "destinationLeaseId", "type": "str"}, - } - - def __init__(self, *, destination_lease_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword destination_lease_id: Required if the destination file has an active infinite lease. - The lease ID specified for this header must match the lease ID of the destination file. If the - request does not include the lease ID or it is not valid, the operation fails with status code - 412 (Precondition Failed). If this header is specified and the destination file does not - currently have an active lease, the operation will also fail with status code 412 (Precondition - Failed). - :paramtype destination_lease_id: str - """ - super().__init__(**kwargs) - self.destination_lease_id = destination_lease_id - - -class DirectoryItem(_serialization.Model): - """A listed directory item. - - All required parameters must be populated in order to send to server. - - :ivar name: Required. - :vartype name: ~azure.storage.fileshare.models.StringEncoded - :ivar file_id: - :vartype file_id: str - :ivar properties: File properties. - :vartype properties: ~azure.storage.fileshare.models.FileProperty - :ivar attributes: - :vartype attributes: str - :ivar permission_key: - :vartype permission_key: str - """ - - _validation = { - "name": {"required": True}, - } - - _attribute_map = { - "name": {"key": "Name", "type": "StringEncoded"}, - "file_id": {"key": "FileId", "type": "str"}, - "properties": {"key": "Properties", "type": "FileProperty"}, - "attributes": {"key": "Attributes", "type": "str"}, - "permission_key": {"key": "PermissionKey", "type": "str"}, - } - _xml_map = {"name": "Directory"} - - def __init__( - self, - *, - name: "_models.StringEncoded", - file_id: Optional[str] = None, - properties: Optional["_models.FileProperty"] = None, - attributes: Optional[str] = None, - permission_key: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Required. - :paramtype name: ~azure.storage.fileshare.models.StringEncoded - :keyword file_id: - :paramtype file_id: str - :keyword properties: File properties. - :paramtype properties: ~azure.storage.fileshare.models.FileProperty - :keyword attributes: - :paramtype attributes: str - :keyword permission_key: - :paramtype permission_key: str - """ - super().__init__(**kwargs) - self.name = name - self.file_id = file_id - self.properties = properties - self.attributes = attributes - self.permission_key = permission_key - - -class FileHTTPHeaders(_serialization.Model): - """Parameter group. - - :ivar file_content_type: Sets the MIME content type of the file. The default type is - 'application/octet-stream'. - :vartype file_content_type: str - :ivar file_content_encoding: Specifies which content encodings have been applied to the file. - :vartype file_content_encoding: str - :ivar file_content_language: Specifies the natural languages used by this resource. - :vartype file_content_language: str - :ivar file_cache_control: Sets the file's cache control. The File service stores this value but - does not use or modify it. - :vartype file_cache_control: str - :ivar file_content_md5: Sets the file's MD5 hash. - :vartype file_content_md5: bytes - :ivar file_content_disposition: Sets the file's Content-Disposition header. - :vartype file_content_disposition: str - """ - - _attribute_map = { - "file_content_type": {"key": "fileContentType", "type": "str"}, - "file_content_encoding": {"key": "fileContentEncoding", "type": "str"}, - "file_content_language": {"key": "fileContentLanguage", "type": "str"}, - "file_cache_control": {"key": "fileCacheControl", "type": "str"}, - "file_content_md5": {"key": "fileContentMD5", "type": "bytearray"}, - "file_content_disposition": {"key": "fileContentDisposition", "type": "str"}, - } - - def __init__( - self, - *, - file_content_type: Optional[str] = None, - file_content_encoding: Optional[str] = None, - file_content_language: Optional[str] = None, - file_cache_control: Optional[str] = None, - file_content_md5: Optional[bytes] = None, - file_content_disposition: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword file_content_type: Sets the MIME content type of the file. The default type is - 'application/octet-stream'. - :paramtype file_content_type: str - :keyword file_content_encoding: Specifies which content encodings have been applied to the - file. - :paramtype file_content_encoding: str - :keyword file_content_language: Specifies the natural languages used by this resource. - :paramtype file_content_language: str - :keyword file_cache_control: Sets the file's cache control. The File service stores this value - but does not use or modify it. - :paramtype file_cache_control: str - :keyword file_content_md5: Sets the file's MD5 hash. - :paramtype file_content_md5: bytes - :keyword file_content_disposition: Sets the file's Content-Disposition header. - :paramtype file_content_disposition: str - """ - super().__init__(**kwargs) - self.file_content_type = file_content_type - self.file_content_encoding = file_content_encoding - self.file_content_language = file_content_language - self.file_cache_control = file_cache_control - self.file_content_md5 = file_content_md5 - self.file_content_disposition = file_content_disposition - - -class FileItem(_serialization.Model): - """A listed file item. - - All required parameters must be populated in order to send to server. - - :ivar name: Required. - :vartype name: ~azure.storage.fileshare.models.StringEncoded - :ivar file_id: - :vartype file_id: str - :ivar properties: File properties. Required. - :vartype properties: ~azure.storage.fileshare.models.FileProperty - :ivar attributes: - :vartype attributes: str - :ivar permission_key: - :vartype permission_key: str - """ - - _validation = { - "name": {"required": True}, - "properties": {"required": True}, - } - - _attribute_map = { - "name": {"key": "Name", "type": "StringEncoded"}, - "file_id": {"key": "FileId", "type": "str"}, - "properties": {"key": "Properties", "type": "FileProperty"}, - "attributes": {"key": "Attributes", "type": "str"}, - "permission_key": {"key": "PermissionKey", "type": "str"}, - } - _xml_map = {"name": "File"} - - def __init__( - self, - *, - name: "_models.StringEncoded", - properties: "_models.FileProperty", - file_id: Optional[str] = None, - attributes: Optional[str] = None, - permission_key: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Required. - :paramtype name: ~azure.storage.fileshare.models.StringEncoded - :keyword file_id: - :paramtype file_id: str - :keyword properties: File properties. Required. - :paramtype properties: ~azure.storage.fileshare.models.FileProperty - :keyword attributes: - :paramtype attributes: str - :keyword permission_key: - :paramtype permission_key: str - """ - super().__init__(**kwargs) - self.name = name - self.file_id = file_id - self.properties = properties - self.attributes = attributes - self.permission_key = permission_key - - -class FileProperty(_serialization.Model): - """File properties. - - All required parameters must be populated in order to send to server. - - :ivar content_length: Content length of the file. This value may not be up-to-date since an SMB - client may have modified the file locally. The value of Content-Length may not reflect that - fact until the handle is closed or the op-lock is broken. To retrieve current property values, - call Get File Properties. Required. - :vartype content_length: int - :ivar creation_time: - :vartype creation_time: ~datetime.datetime - :ivar last_access_time: - :vartype last_access_time: ~datetime.datetime - :ivar last_write_time: - :vartype last_write_time: ~datetime.datetime - :ivar change_time: - :vartype change_time: ~datetime.datetime - :ivar last_modified: - :vartype last_modified: ~datetime.datetime - :ivar etag: - :vartype etag: str - """ - - _validation = { - "content_length": {"required": True}, - } - - _attribute_map = { - "content_length": {"key": "Content-Length", "type": "int"}, - "creation_time": {"key": "CreationTime", "type": "iso-8601"}, - "last_access_time": {"key": "LastAccessTime", "type": "iso-8601"}, - "last_write_time": {"key": "LastWriteTime", "type": "iso-8601"}, - "change_time": {"key": "ChangeTime", "type": "iso-8601"}, - "last_modified": {"key": "Last-Modified", "type": "rfc-1123"}, - "etag": {"key": "Etag", "type": "str"}, - } - - def __init__( - self, - *, - content_length: int, - creation_time: Optional[datetime.datetime] = None, - last_access_time: Optional[datetime.datetime] = None, - last_write_time: Optional[datetime.datetime] = None, - change_time: Optional[datetime.datetime] = None, - last_modified: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword content_length: Content length of the file. This value may not be up-to-date since an - SMB client may have modified the file locally. The value of Content-Length may not reflect that - fact until the handle is closed or the op-lock is broken. To retrieve current property values, - call Get File Properties. Required. - :paramtype content_length: int - :keyword creation_time: - :paramtype creation_time: ~datetime.datetime - :keyword last_access_time: - :paramtype last_access_time: ~datetime.datetime - :keyword last_write_time: - :paramtype last_write_time: ~datetime.datetime - :keyword change_time: - :paramtype change_time: ~datetime.datetime - :keyword last_modified: - :paramtype last_modified: ~datetime.datetime - :keyword etag: - :paramtype etag: str - """ - super().__init__(**kwargs) - self.content_length = content_length - self.creation_time = creation_time - self.last_access_time = last_access_time - self.last_write_time = last_write_time - self.change_time = change_time - self.last_modified = last_modified - self.etag = etag - - -class FileRange(_serialization.Model): - """An Azure Storage file range. - - All required parameters must be populated in order to send to server. - - :ivar start: Start of the range. Required. - :vartype start: int - :ivar end: End of the range. Required. - :vartype end: int - """ - - _validation = { - "start": {"required": True}, - "end": {"required": True}, - } - - _attribute_map = { - "start": {"key": "Start", "type": "int"}, - "end": {"key": "End", "type": "int"}, - } - _xml_map = {"name": "Range"} - - def __init__(self, *, start: int, end: int, **kwargs: Any) -> None: - """ - :keyword start: Start of the range. Required. - :paramtype start: int - :keyword end: End of the range. Required. - :paramtype end: int - """ - super().__init__(**kwargs) - self.start = start - self.end = end - - -class FilesAndDirectoriesListSegment(_serialization.Model): - """Abstract for entries that can be listed from Directory. - - All required parameters must be populated in order to send to server. - - :ivar directory_items: Required. - :vartype directory_items: list[~azure.storage.fileshare.models.DirectoryItem] - :ivar file_items: Required. - :vartype file_items: list[~azure.storage.fileshare.models.FileItem] - """ - - _validation = { - "directory_items": {"required": True}, - "file_items": {"required": True}, - } - - _attribute_map = { - "directory_items": {"key": "DirectoryItems", "type": "[DirectoryItem]", "xml": {"itemsName": "Directory"}}, - "file_items": {"key": "FileItems", "type": "[FileItem]", "xml": {"itemsName": "File"}}, - } - _xml_map = {"name": "Entries"} - - def __init__( - self, *, directory_items: list["_models.DirectoryItem"], file_items: list["_models.FileItem"], **kwargs: Any - ) -> None: - """ - :keyword directory_items: Required. - :paramtype directory_items: list[~azure.storage.fileshare.models.DirectoryItem] - :keyword file_items: Required. - :paramtype file_items: list[~azure.storage.fileshare.models.FileItem] - """ - super().__init__(**kwargs) - self.directory_items = directory_items - self.file_items = file_items - - -class HandleItem(_serialization.Model): - """A listed Azure Storage handle item. - - All required parameters must be populated in order to send to server. - - :ivar handle_id: XSMB service handle ID. Required. - :vartype handle_id: str - :ivar path: Required. - :vartype path: ~azure.storage.fileshare.models.StringEncoded - :ivar file_id: FileId uniquely identifies the file or directory. Required. - :vartype file_id: str - :ivar parent_id: ParentId uniquely identifies the parent directory of the object. - :vartype parent_id: str - :ivar session_id: SMB session ID in context of which the file handle was opened. Required. - :vartype session_id: str - :ivar client_ip: Client IP that opened the handle. Required. - :vartype client_ip: str - :ivar client_name: Name of the client machine where the share is being mounted. Required. - :vartype client_name: str - :ivar open_time: Time when the session that previously opened the handle has last been - reconnected. (UTC). Required. - :vartype open_time: ~datetime.datetime - :ivar last_reconnect_time: Time handle was last connected to (UTC). - :vartype last_reconnect_time: ~datetime.datetime - :ivar access_right_list: - :vartype access_right_list: list[str or ~azure.storage.fileshare.models.AccessRight] - """ - - _validation = { - "handle_id": {"required": True}, - "path": {"required": True}, - "file_id": {"required": True}, - "session_id": {"required": True}, - "client_ip": {"required": True}, - "client_name": {"required": True}, - "open_time": {"required": True}, - } - - _attribute_map = { - "handle_id": {"key": "HandleId", "type": "str"}, - "path": {"key": "Path", "type": "StringEncoded"}, - "file_id": {"key": "FileId", "type": "str"}, - "parent_id": {"key": "ParentId", "type": "str"}, - "session_id": {"key": "SessionId", "type": "str"}, - "client_ip": {"key": "ClientIp", "type": "str"}, - "client_name": {"key": "ClientName", "type": "str"}, - "open_time": {"key": "OpenTime", "type": "rfc-1123"}, - "last_reconnect_time": {"key": "LastReconnectTime", "type": "rfc-1123"}, - "access_right_list": {"key": "AccessRightList", "type": "[str]", "xml": {"wrapped": True}}, - } - _xml_map = {"name": "Handle"} - - def __init__( - self, - *, - handle_id: str, - path: "_models.StringEncoded", - file_id: str, - session_id: str, - client_ip: str, - client_name: str, - open_time: datetime.datetime, - parent_id: Optional[str] = None, - last_reconnect_time: Optional[datetime.datetime] = None, - access_right_list: Optional[list[Union[str, "_models.AccessRight"]]] = None, - **kwargs: Any - ) -> None: - """ - :keyword handle_id: XSMB service handle ID. Required. - :paramtype handle_id: str - :keyword path: Required. - :paramtype path: ~azure.storage.fileshare.models.StringEncoded - :keyword file_id: FileId uniquely identifies the file or directory. Required. - :paramtype file_id: str - :keyword parent_id: ParentId uniquely identifies the parent directory of the object. - :paramtype parent_id: str - :keyword session_id: SMB session ID in context of which the file handle was opened. Required. - :paramtype session_id: str - :keyword client_ip: Client IP that opened the handle. Required. - :paramtype client_ip: str - :keyword client_name: Name of the client machine where the share is being mounted. Required. - :paramtype client_name: str - :keyword open_time: Time when the session that previously opened the handle has last been - reconnected. (UTC). Required. - :paramtype open_time: ~datetime.datetime - :keyword last_reconnect_time: Time handle was last connected to (UTC). - :paramtype last_reconnect_time: ~datetime.datetime - :keyword access_right_list: - :paramtype access_right_list: list[str or ~azure.storage.fileshare.models.AccessRight] - """ - super().__init__(**kwargs) - self.handle_id = handle_id - self.path = path - self.file_id = file_id - self.parent_id = parent_id - self.session_id = session_id - self.client_ip = client_ip - self.client_name = client_name - self.open_time = open_time - self.last_reconnect_time = last_reconnect_time - self.access_right_list = access_right_list - - -class KeyInfo(_serialization.Model): - """Key information. - - All required parameters must be populated in order to send to server. - - :ivar start: The date-time the key is active in ISO 8601 UTC time. - :vartype start: str - :ivar expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :vartype expiry: str - :ivar delegated_user_tid: The delegated user tenant id in Azure AD. - :vartype delegated_user_tid: str - """ - - _validation = { - "expiry": {"required": True}, - } - - _attribute_map = { - "start": {"key": "Start", "type": "str"}, - "expiry": {"key": "Expiry", "type": "str"}, - "delegated_user_tid": {"key": "DelegatedUserTid", "type": "str"}, - } - - def __init__( - self, *, expiry: str, start: Optional[str] = None, delegated_user_tid: Optional[str] = None, **kwargs: Any - ) -> None: - """ - :keyword start: The date-time the key is active in ISO 8601 UTC time. - :paramtype start: str - :keyword expiry: The date-time the key expires in ISO 8601 UTC time. Required. - :paramtype expiry: str - :keyword delegated_user_tid: The delegated user tenant id in Azure AD. - :paramtype delegated_user_tid: str - """ - super().__init__(**kwargs) - self.start = start - self.expiry = expiry - self.delegated_user_tid = delegated_user_tid - - -class LeaseAccessConditions(_serialization.Model): - """Parameter group. - - :ivar lease_id: If specified, the operation only succeeds if the resource's lease is active and - matches this ID. - :vartype lease_id: str - """ - - _attribute_map = { - "lease_id": {"key": "leaseId", "type": "str"}, - } - - def __init__(self, *, lease_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword lease_id: If specified, the operation only succeeds if the resource's lease is active - and matches this ID. - :paramtype lease_id: str - """ - super().__init__(**kwargs) - self.lease_id = lease_id - - -class ListFilesAndDirectoriesSegmentResponse(_serialization.Model): - """An enumeration of directories and files. - - All required parameters must be populated in order to send to server. - - :ivar service_endpoint: Required. - :vartype service_endpoint: str - :ivar share_name: Required. - :vartype share_name: str - :ivar share_snapshot: - :vartype share_snapshot: str - :ivar encoded: - :vartype encoded: bool - :ivar directory_path: Required. - :vartype directory_path: str - :ivar prefix: Required. - :vartype prefix: ~azure.storage.fileshare.models.StringEncoded - :ivar marker: - :vartype marker: str - :ivar max_results: - :vartype max_results: int - :ivar segment: Abstract for entries that can be listed from Directory. Required. - :vartype segment: ~azure.storage.fileshare.models.FilesAndDirectoriesListSegment - :ivar next_marker: Required. - :vartype next_marker: str - :ivar directory_id: - :vartype directory_id: str - """ - - _validation = { - "service_endpoint": {"required": True}, - "share_name": {"required": True}, - "directory_path": {"required": True}, - "prefix": {"required": True}, - "segment": {"required": True}, - "next_marker": {"required": True}, - } - - _attribute_map = { - "service_endpoint": {"key": "ServiceEndpoint", "type": "str", "xml": {"attr": True}}, - "share_name": {"key": "ShareName", "type": "str", "xml": {"attr": True}}, - "share_snapshot": {"key": "ShareSnapshot", "type": "str", "xml": {"attr": True}}, - "encoded": {"key": "Encoded", "type": "bool", "xml": {"attr": True}}, - "directory_path": {"key": "DirectoryPath", "type": "str", "xml": {"attr": True}}, - "prefix": {"key": "Prefix", "type": "StringEncoded"}, - "marker": {"key": "Marker", "type": "str"}, - "max_results": {"key": "MaxResults", "type": "int"}, - "segment": {"key": "Segment", "type": "FilesAndDirectoriesListSegment"}, - "next_marker": {"key": "NextMarker", "type": "str"}, - "directory_id": {"key": "DirectoryId", "type": "str"}, - } - _xml_map = {"name": "EnumerationResults"} - - def __init__( - self, - *, - service_endpoint: str, - share_name: str, - directory_path: str, - prefix: "_models.StringEncoded", - segment: "_models.FilesAndDirectoriesListSegment", - next_marker: str, - share_snapshot: Optional[str] = None, - encoded: Optional[bool] = None, - marker: Optional[str] = None, - max_results: Optional[int] = None, - directory_id: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword service_endpoint: Required. - :paramtype service_endpoint: str - :keyword share_name: Required. - :paramtype share_name: str - :keyword share_snapshot: - :paramtype share_snapshot: str - :keyword encoded: - :paramtype encoded: bool - :keyword directory_path: Required. - :paramtype directory_path: str - :keyword prefix: Required. - :paramtype prefix: ~azure.storage.fileshare.models.StringEncoded - :keyword marker: - :paramtype marker: str - :keyword max_results: - :paramtype max_results: int - :keyword segment: Abstract for entries that can be listed from Directory. Required. - :paramtype segment: ~azure.storage.fileshare.models.FilesAndDirectoriesListSegment - :keyword next_marker: Required. - :paramtype next_marker: str - :keyword directory_id: - :paramtype directory_id: str - """ - super().__init__(**kwargs) - self.service_endpoint = service_endpoint - self.share_name = share_name - self.share_snapshot = share_snapshot - self.encoded = encoded - self.directory_path = directory_path - self.prefix = prefix - self.marker = marker - self.max_results = max_results - self.segment = segment - self.next_marker = next_marker - self.directory_id = directory_id - - -class ListHandlesResponse(_serialization.Model): - """An enumeration of handles. - - All required parameters must be populated in order to send to server. - - :ivar handle_list: - :vartype handle_list: list[~azure.storage.fileshare.models.HandleItem] - :ivar next_marker: Required. - :vartype next_marker: str - """ - - _validation = { - "next_marker": {"required": True}, - } - - _attribute_map = { - "handle_list": { - "key": "HandleList", - "type": "[HandleItem]", - "xml": {"name": "Entries", "wrapped": True, "itemsName": "Handle"}, - }, - "next_marker": {"key": "NextMarker", "type": "str"}, - } - _xml_map = {"name": "EnumerationResults"} - - def __init__( - self, *, next_marker: str, handle_list: Optional[list["_models.HandleItem"]] = None, **kwargs: Any - ) -> None: - """ - :keyword handle_list: - :paramtype handle_list: list[~azure.storage.fileshare.models.HandleItem] - :keyword next_marker: Required. - :paramtype next_marker: str - """ - super().__init__(**kwargs) - self.handle_list = handle_list - self.next_marker = next_marker - - -class ListSharesResponse(_serialization.Model): - """An enumeration of shares. - - All required parameters must be populated in order to send to server. - - :ivar service_endpoint: Required. - :vartype service_endpoint: str - :ivar prefix: - :vartype prefix: str - :ivar marker: - :vartype marker: str - :ivar max_results: - :vartype max_results: int - :ivar share_items: - :vartype share_items: list[~azure.storage.fileshare.models.ShareItemInternal] - :ivar next_marker: Required. - :vartype next_marker: str - """ - - _validation = { - "service_endpoint": {"required": True}, - "next_marker": {"required": True}, - } - - _attribute_map = { - "service_endpoint": {"key": "ServiceEndpoint", "type": "str", "xml": {"attr": True}}, - "prefix": {"key": "Prefix", "type": "str"}, - "marker": {"key": "Marker", "type": "str"}, - "max_results": {"key": "MaxResults", "type": "int"}, - "share_items": { - "key": "ShareItems", - "type": "[ShareItemInternal]", - "xml": {"name": "Shares", "wrapped": True, "itemsName": "Share"}, - }, - "next_marker": {"key": "NextMarker", "type": "str"}, - } - _xml_map = {"name": "EnumerationResults"} - - def __init__( - self, - *, - service_endpoint: str, - next_marker: str, - prefix: Optional[str] = None, - marker: Optional[str] = None, - max_results: Optional[int] = None, - share_items: Optional[list["_models.ShareItemInternal"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword service_endpoint: Required. - :paramtype service_endpoint: str - :keyword prefix: - :paramtype prefix: str - :keyword marker: - :paramtype marker: str - :keyword max_results: - :paramtype max_results: int - :keyword share_items: - :paramtype share_items: list[~azure.storage.fileshare.models.ShareItemInternal] - :keyword next_marker: Required. - :paramtype next_marker: str - """ - super().__init__(**kwargs) - self.service_endpoint = service_endpoint - self.prefix = prefix - self.marker = marker - self.max_results = max_results - self.share_items = share_items - self.next_marker = next_marker - - -class Metrics(_serialization.Model): - """Storage Analytics metrics for file service. - - All required parameters must be populated in order to send to server. - - :ivar version: The version of Storage Analytics to configure. Required. - :vartype version: str - :ivar enabled: Indicates whether metrics are enabled for the File service. Required. - :vartype enabled: bool - :ivar include_apis: Indicates whether metrics should generate summary statistics for called API - operations. - :vartype include_apis: bool - :ivar retention_policy: The retention policy. - :vartype retention_policy: ~azure.storage.fileshare.models.RetentionPolicy - """ - - _validation = { - "version": {"required": True}, - "enabled": {"required": True}, - } - - _attribute_map = { - "version": {"key": "Version", "type": "str"}, - "enabled": {"key": "Enabled", "type": "bool"}, - "include_apis": {"key": "IncludeAPIs", "type": "bool"}, - "retention_policy": {"key": "RetentionPolicy", "type": "RetentionPolicy"}, - } - - def __init__( - self, - *, - version: str, - enabled: bool, - include_apis: Optional[bool] = None, - retention_policy: Optional["_models.RetentionPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword version: The version of Storage Analytics to configure. Required. - :paramtype version: str - :keyword enabled: Indicates whether metrics are enabled for the File service. Required. - :paramtype enabled: bool - :keyword include_apis: Indicates whether metrics should generate summary statistics for called - API operations. - :paramtype include_apis: bool - :keyword retention_policy: The retention policy. - :paramtype retention_policy: ~azure.storage.fileshare.models.RetentionPolicy - """ - super().__init__(**kwargs) - self.version = version - self.enabled = enabled - self.include_apis = include_apis - self.retention_policy = retention_policy - - -class RetentionPolicy(_serialization.Model): - """The retention policy. - - All required parameters must be populated in order to send to server. - - :ivar enabled: Indicates whether a retention policy is enabled for the File service. If false, - metrics data is retained, and the user is responsible for deleting it. Required. - :vartype enabled: bool - :ivar days: Indicates the number of days that metrics data should be retained. All data older - than this value will be deleted. Metrics data is deleted on a best-effort basis after the - retention period expires. - :vartype days: int - """ - - _validation = { - "enabled": {"required": True}, - "days": {"maximum": 365, "minimum": 1}, - } - - _attribute_map = { - "enabled": {"key": "Enabled", "type": "bool"}, - "days": {"key": "Days", "type": "int"}, - } - - def __init__(self, *, enabled: bool, days: Optional[int] = None, **kwargs: Any) -> None: - """ - :keyword enabled: Indicates whether a retention policy is enabled for the File service. If - false, metrics data is retained, and the user is responsible for deleting it. Required. - :paramtype enabled: bool - :keyword days: Indicates the number of days that metrics data should be retained. All data - older than this value will be deleted. Metrics data is deleted on a best-effort basis after the - retention period expires. - :paramtype days: int - """ - super().__init__(**kwargs) - self.enabled = enabled - self.days = days - - -class ShareFileRangeList(_serialization.Model): - """The list of file ranges. - - :ivar ranges: - :vartype ranges: list[~azure.storage.fileshare.models.FileRange] - :ivar clear_ranges: - :vartype clear_ranges: list[~azure.storage.fileshare.models.ClearRange] - """ - - _attribute_map = { - "ranges": {"key": "Ranges", "type": "[FileRange]", "xml": {"itemsName": "Range"}}, - "clear_ranges": {"key": "ClearRanges", "type": "[ClearRange]", "xml": {"itemsName": "ClearRange"}}, - } - - def __init__( - self, - *, - ranges: Optional[list["_models.FileRange"]] = None, - clear_ranges: Optional[list["_models.ClearRange"]] = None, - **kwargs: Any - ) -> None: - """ - :keyword ranges: - :paramtype ranges: list[~azure.storage.fileshare.models.FileRange] - :keyword clear_ranges: - :paramtype clear_ranges: list[~azure.storage.fileshare.models.ClearRange] - """ - super().__init__(**kwargs) - self.ranges = ranges - self.clear_ranges = clear_ranges - - -class ShareItemInternal(_serialization.Model): - """A listed Azure Storage share item. - - All required parameters must be populated in order to send to server. - - :ivar name: Required. - :vartype name: str - :ivar snapshot: - :vartype snapshot: str - :ivar deleted: - :vartype deleted: bool - :ivar version: - :vartype version: str - :ivar properties: Properties of a share. Required. - :vartype properties: ~azure.storage.fileshare.models.SharePropertiesInternal - :ivar metadata: Dictionary of :code:``. - :vartype metadata: dict[str, str] - """ - - _validation = { - "name": {"required": True}, - "properties": {"required": True}, - } - - _attribute_map = { - "name": {"key": "Name", "type": "str"}, - "snapshot": {"key": "Snapshot", "type": "str"}, - "deleted": {"key": "Deleted", "type": "bool"}, - "version": {"key": "Version", "type": "str"}, - "properties": {"key": "Properties", "type": "SharePropertiesInternal"}, - "metadata": {"key": "Metadata", "type": "{str}"}, - } - _xml_map = {"name": "Share"} - - def __init__( - self, - *, - name: str, - properties: "_models.SharePropertiesInternal", - snapshot: Optional[str] = None, - deleted: Optional[bool] = None, - version: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - **kwargs: Any - ) -> None: - """ - :keyword name: Required. - :paramtype name: str - :keyword snapshot: - :paramtype snapshot: str - :keyword deleted: - :paramtype deleted: bool - :keyword version: - :paramtype version: str - :keyword properties: Properties of a share. Required. - :paramtype properties: ~azure.storage.fileshare.models.SharePropertiesInternal - :keyword metadata: Dictionary of :code:``. - :paramtype metadata: dict[str, str] - """ - super().__init__(**kwargs) - self.name = name - self.snapshot = snapshot - self.deleted = deleted - self.version = version - self.properties = properties - self.metadata = metadata - - -class ShareNfsSettings(_serialization.Model): - """Settings for SMB protocol. - - :ivar encryption_in_transit: Enable or disable encryption in transit. - :vartype encryption_in_transit: - ~azure.storage.fileshare.models.ShareNfsSettingsEncryptionInTransit - """ - - _attribute_map = { - "encryption_in_transit": {"key": "EncryptionInTransit", "type": "ShareNfsSettingsEncryptionInTransit"}, - } - _xml_map = {"name": "NFS"} - - def __init__( - self, *, encryption_in_transit: Optional["_models.ShareNfsSettingsEncryptionInTransit"] = None, **kwargs: Any - ) -> None: - """ - :keyword encryption_in_transit: Enable or disable encryption in transit. - :paramtype encryption_in_transit: - ~azure.storage.fileshare.models.ShareNfsSettingsEncryptionInTransit - """ - super().__init__(**kwargs) - self.encryption_in_transit = encryption_in_transit - - -class ShareNfsSettingsEncryptionInTransit(_serialization.Model): - """Enable or disable encryption in transit. - - :ivar required: If encryption in transit is required. - :vartype required: bool - """ - - _attribute_map = { - "required": {"key": "Required", "type": "bool"}, - } - - def __init__(self, *, required: Optional[bool] = None, **kwargs: Any) -> None: - """ - :keyword required: If encryption in transit is required. - :paramtype required: bool - """ - super().__init__(**kwargs) - self.required = required - - -class SharePermission(_serialization.Model): - """A permission (a security descriptor) at the share level. - - All required parameters must be populated in order to send to server. - - :ivar permission: The permission in the Security Descriptor Definition Language (SDDL). - Required. - :vartype permission: str - :ivar format: Known values are: "Sddl" and "Binary". - :vartype format: str or ~azure.storage.fileshare.models.FilePermissionFormat - """ - - _validation = { - "permission": {"required": True}, - } - - _attribute_map = { - "permission": {"key": "permission", "type": "str"}, - "format": {"key": "format", "type": "str"}, - } - - def __init__( - self, *, permission: str, format: Optional[Union[str, "_models.FilePermissionFormat"]] = None, **kwargs: Any - ) -> None: - """ - :keyword permission: The permission in the Security Descriptor Definition Language (SDDL). - Required. - :paramtype permission: str - :keyword format: Known values are: "Sddl" and "Binary". - :paramtype format: str or ~azure.storage.fileshare.models.FilePermissionFormat - """ - super().__init__(**kwargs) - self.permission = permission - self.format = format - - -class SharePropertiesInternal(_serialization.Model): - """Properties of a share. - - All required parameters must be populated in order to send to server. - - :ivar last_modified: Required. - :vartype last_modified: ~datetime.datetime - :ivar etag: Required. - :vartype etag: str - :ivar quota: Required. - :vartype quota: int - :ivar provisioned_iops: - :vartype provisioned_iops: int - :ivar provisioned_ingress_m_bps: - :vartype provisioned_ingress_m_bps: int - :ivar provisioned_egress_m_bps: - :vartype provisioned_egress_m_bps: int - :ivar provisioned_bandwidth_mi_bps: - :vartype provisioned_bandwidth_mi_bps: int - :ivar next_allowed_quota_downgrade_time: - :vartype next_allowed_quota_downgrade_time: ~datetime.datetime - :ivar deleted_time: - :vartype deleted_time: ~datetime.datetime - :ivar remaining_retention_days: - :vartype remaining_retention_days: int - :ivar access_tier: - :vartype access_tier: str - :ivar access_tier_change_time: - :vartype access_tier_change_time: ~datetime.datetime - :ivar access_tier_transition_state: - :vartype access_tier_transition_state: str - :ivar lease_status: The current lease status of the share. Known values are: "locked" and - "unlocked". - :vartype lease_status: str or ~azure.storage.fileshare.models.LeaseStatusType - :ivar lease_state: Lease state of the share. Known values are: "available", "leased", - "expired", "breaking", and "broken". - :vartype lease_state: str or ~azure.storage.fileshare.models.LeaseStateType - :ivar lease_duration: When a share is leased, specifies whether the lease is of infinite or - fixed duration. Known values are: "infinite" and "fixed". - :vartype lease_duration: str or ~azure.storage.fileshare.models.LeaseDurationType - :ivar enabled_protocols: - :vartype enabled_protocols: str - :ivar root_squash: Known values are: "NoRootSquash", "RootSquash", and "AllSquash". - :vartype root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash - :ivar enable_snapshot_virtual_directory_access: - :vartype enable_snapshot_virtual_directory_access: bool - :ivar paid_bursting_enabled: - :vartype paid_bursting_enabled: bool - :ivar paid_bursting_max_iops: - :vartype paid_bursting_max_iops: int - :ivar paid_bursting_max_bandwidth_mibps: - :vartype paid_bursting_max_bandwidth_mibps: int - :ivar included_burst_iops: - :vartype included_burst_iops: int - :ivar max_burst_credits_for_iops: - :vartype max_burst_credits_for_iops: int - :ivar next_allowed_provisioned_iops_downgrade_time: - :vartype next_allowed_provisioned_iops_downgrade_time: ~datetime.datetime - :ivar next_allowed_provisioned_bandwidth_downgrade_time: - :vartype next_allowed_provisioned_bandwidth_downgrade_time: ~datetime.datetime - :ivar enable_smb_directory_lease: - :vartype enable_smb_directory_lease: bool - """ - - _validation = { - "last_modified": {"required": True}, - "etag": {"required": True}, - "quota": {"required": True}, - } - - _attribute_map = { - "last_modified": {"key": "Last-Modified", "type": "rfc-1123"}, - "etag": {"key": "Etag", "type": "str"}, - "quota": {"key": "Quota", "type": "int"}, - "provisioned_iops": {"key": "ProvisionedIops", "type": "int"}, - "provisioned_ingress_m_bps": {"key": "ProvisionedIngressMBps", "type": "int"}, - "provisioned_egress_m_bps": {"key": "ProvisionedEgressMBps", "type": "int"}, - "provisioned_bandwidth_mi_bps": {"key": "ProvisionedBandwidthMiBps", "type": "int"}, - "next_allowed_quota_downgrade_time": {"key": "NextAllowedQuotaDowngradeTime", "type": "rfc-1123"}, - "deleted_time": {"key": "DeletedTime", "type": "rfc-1123"}, - "remaining_retention_days": {"key": "RemainingRetentionDays", "type": "int"}, - "access_tier": {"key": "AccessTier", "type": "str"}, - "access_tier_change_time": {"key": "AccessTierChangeTime", "type": "rfc-1123"}, - "access_tier_transition_state": {"key": "AccessTierTransitionState", "type": "str"}, - "lease_status": {"key": "LeaseStatus", "type": "str"}, - "lease_state": {"key": "LeaseState", "type": "str"}, - "lease_duration": {"key": "LeaseDuration", "type": "str"}, - "enabled_protocols": {"key": "EnabledProtocols", "type": "str"}, - "root_squash": {"key": "RootSquash", "type": "str"}, - "enable_snapshot_virtual_directory_access": {"key": "EnableSnapshotVirtualDirectoryAccess", "type": "bool"}, - "paid_bursting_enabled": {"key": "PaidBurstingEnabled", "type": "bool"}, - "paid_bursting_max_iops": {"key": "PaidBurstingMaxIops", "type": "int"}, - "paid_bursting_max_bandwidth_mibps": {"key": "PaidBurstingMaxBandwidthMibps", "type": "int"}, - "included_burst_iops": {"key": "IncludedBurstIops", "type": "int"}, - "max_burst_credits_for_iops": {"key": "MaxBurstCreditsForIops", "type": "int"}, - "next_allowed_provisioned_iops_downgrade_time": { - "key": "NextAllowedProvisionedIopsDowngradeTime", - "type": "rfc-1123", - }, - "next_allowed_provisioned_bandwidth_downgrade_time": { - "key": "NextAllowedProvisionedBandwidthDowngradeTime", - "type": "rfc-1123", - }, - "enable_smb_directory_lease": {"key": "EnableSmbDirectoryLease", "type": "bool"}, - } - - def __init__( # pylint: disable=too-many-locals - self, - *, - last_modified: datetime.datetime, - etag: str, - quota: int, - provisioned_iops: Optional[int] = None, - provisioned_ingress_m_bps: Optional[int] = None, - provisioned_egress_m_bps: Optional[int] = None, - provisioned_bandwidth_mi_bps: Optional[int] = None, - next_allowed_quota_downgrade_time: Optional[datetime.datetime] = None, - deleted_time: Optional[datetime.datetime] = None, - remaining_retention_days: Optional[int] = None, - access_tier: Optional[str] = None, - access_tier_change_time: Optional[datetime.datetime] = None, - access_tier_transition_state: Optional[str] = None, - lease_status: Optional[Union[str, "_models.LeaseStatusType"]] = None, - lease_state: Optional[Union[str, "_models.LeaseStateType"]] = None, - lease_duration: Optional[Union[str, "_models.LeaseDurationType"]] = None, - enabled_protocols: Optional[str] = None, - root_squash: Optional[Union[str, "_models.ShareRootSquash"]] = None, - enable_snapshot_virtual_directory_access: Optional[bool] = None, - paid_bursting_enabled: Optional[bool] = None, - paid_bursting_max_iops: Optional[int] = None, - paid_bursting_max_bandwidth_mibps: Optional[int] = None, - included_burst_iops: Optional[int] = None, - max_burst_credits_for_iops: Optional[int] = None, - next_allowed_provisioned_iops_downgrade_time: Optional[datetime.datetime] = None, - next_allowed_provisioned_bandwidth_downgrade_time: Optional[datetime.datetime] = None, - enable_smb_directory_lease: Optional[bool] = None, - **kwargs: Any - ) -> None: - """ - :keyword last_modified: Required. - :paramtype last_modified: ~datetime.datetime - :keyword etag: Required. - :paramtype etag: str - :keyword quota: Required. - :paramtype quota: int - :keyword provisioned_iops: - :paramtype provisioned_iops: int - :keyword provisioned_ingress_m_bps: - :paramtype provisioned_ingress_m_bps: int - :keyword provisioned_egress_m_bps: - :paramtype provisioned_egress_m_bps: int - :keyword provisioned_bandwidth_mi_bps: - :paramtype provisioned_bandwidth_mi_bps: int - :keyword next_allowed_quota_downgrade_time: - :paramtype next_allowed_quota_downgrade_time: ~datetime.datetime - :keyword deleted_time: - :paramtype deleted_time: ~datetime.datetime - :keyword remaining_retention_days: - :paramtype remaining_retention_days: int - :keyword access_tier: - :paramtype access_tier: str - :keyword access_tier_change_time: - :paramtype access_tier_change_time: ~datetime.datetime - :keyword access_tier_transition_state: - :paramtype access_tier_transition_state: str - :keyword lease_status: The current lease status of the share. Known values are: "locked" and - "unlocked". - :paramtype lease_status: str or ~azure.storage.fileshare.models.LeaseStatusType - :keyword lease_state: Lease state of the share. Known values are: "available", "leased", - "expired", "breaking", and "broken". - :paramtype lease_state: str or ~azure.storage.fileshare.models.LeaseStateType - :keyword lease_duration: When a share is leased, specifies whether the lease is of infinite or - fixed duration. Known values are: "infinite" and "fixed". - :paramtype lease_duration: str or ~azure.storage.fileshare.models.LeaseDurationType - :keyword enabled_protocols: - :paramtype enabled_protocols: str - :keyword root_squash: Known values are: "NoRootSquash", "RootSquash", and "AllSquash". - :paramtype root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash - :keyword enable_snapshot_virtual_directory_access: - :paramtype enable_snapshot_virtual_directory_access: bool - :keyword paid_bursting_enabled: - :paramtype paid_bursting_enabled: bool - :keyword paid_bursting_max_iops: - :paramtype paid_bursting_max_iops: int - :keyword paid_bursting_max_bandwidth_mibps: - :paramtype paid_bursting_max_bandwidth_mibps: int - :keyword included_burst_iops: - :paramtype included_burst_iops: int - :keyword max_burst_credits_for_iops: - :paramtype max_burst_credits_for_iops: int - :keyword next_allowed_provisioned_iops_downgrade_time: - :paramtype next_allowed_provisioned_iops_downgrade_time: ~datetime.datetime - :keyword next_allowed_provisioned_bandwidth_downgrade_time: - :paramtype next_allowed_provisioned_bandwidth_downgrade_time: ~datetime.datetime - :keyword enable_smb_directory_lease: - :paramtype enable_smb_directory_lease: bool - """ - super().__init__(**kwargs) - self.last_modified = last_modified - self.etag = etag - self.quota = quota - self.provisioned_iops = provisioned_iops - self.provisioned_ingress_m_bps = provisioned_ingress_m_bps - self.provisioned_egress_m_bps = provisioned_egress_m_bps - self.provisioned_bandwidth_mi_bps = provisioned_bandwidth_mi_bps - self.next_allowed_quota_downgrade_time = next_allowed_quota_downgrade_time - self.deleted_time = deleted_time - self.remaining_retention_days = remaining_retention_days - self.access_tier = access_tier - self.access_tier_change_time = access_tier_change_time - self.access_tier_transition_state = access_tier_transition_state - self.lease_status = lease_status - self.lease_state = lease_state - self.lease_duration = lease_duration - self.enabled_protocols = enabled_protocols - self.root_squash = root_squash - self.enable_snapshot_virtual_directory_access = enable_snapshot_virtual_directory_access - self.paid_bursting_enabled = paid_bursting_enabled - self.paid_bursting_max_iops = paid_bursting_max_iops - self.paid_bursting_max_bandwidth_mibps = paid_bursting_max_bandwidth_mibps - self.included_burst_iops = included_burst_iops - self.max_burst_credits_for_iops = max_burst_credits_for_iops - self.next_allowed_provisioned_iops_downgrade_time = next_allowed_provisioned_iops_downgrade_time - self.next_allowed_provisioned_bandwidth_downgrade_time = next_allowed_provisioned_bandwidth_downgrade_time - self.enable_smb_directory_lease = enable_smb_directory_lease - - -class ShareProtocolSettings(_serialization.Model): - """Protocol settings. - - :ivar smb: Settings for SMB protocol. - :vartype smb: ~azure.storage.fileshare.models.ShareSmbSettings - :ivar nfs: Settings for NFS protocol. - :vartype nfs: ~azure.storage.fileshare.models.ShareNfsSettings - """ - - _attribute_map = { - "smb": {"key": "Smb", "type": "ShareSmbSettings"}, - "nfs": {"key": "Nfs", "type": "ShareNfsSettings"}, - } - _xml_map = {"name": "ProtocolSettings"} - - def __init__( - self, - *, - smb: Optional["_models.ShareSmbSettings"] = None, - nfs: Optional["_models.ShareNfsSettings"] = None, - **kwargs: Any - ) -> None: - """ - :keyword smb: Settings for SMB protocol. - :paramtype smb: ~azure.storage.fileshare.models.ShareSmbSettings - :keyword nfs: Settings for NFS protocol. - :paramtype nfs: ~azure.storage.fileshare.models.ShareNfsSettings - """ - super().__init__(**kwargs) - self.smb = smb - self.nfs = nfs - - -class ShareSmbSettings(_serialization.Model): - """Settings for SMB protocol. - - :ivar multichannel: Settings for SMB Multichannel. - :vartype multichannel: ~azure.storage.fileshare.models.SmbMultichannel - :ivar encryption_in_transit: Enable or disable encryption in transit. - :vartype encryption_in_transit: - ~azure.storage.fileshare.models.ShareSmbSettingsEncryptionInTransit - """ - - _attribute_map = { - "multichannel": {"key": "Multichannel", "type": "SmbMultichannel"}, - "encryption_in_transit": {"key": "EncryptionInTransit", "type": "ShareSmbSettingsEncryptionInTransit"}, - } - _xml_map = {"name": "SMB"} - - def __init__( - self, - *, - multichannel: Optional["_models.SmbMultichannel"] = None, - encryption_in_transit: Optional["_models.ShareSmbSettingsEncryptionInTransit"] = None, - **kwargs: Any - ) -> None: - """ - :keyword multichannel: Settings for SMB Multichannel. - :paramtype multichannel: ~azure.storage.fileshare.models.SmbMultichannel - :keyword encryption_in_transit: Enable or disable encryption in transit. - :paramtype encryption_in_transit: - ~azure.storage.fileshare.models.ShareSmbSettingsEncryptionInTransit - """ - super().__init__(**kwargs) - self.multichannel = multichannel - self.encryption_in_transit = encryption_in_transit - - -class ShareSmbSettingsEncryptionInTransit(_serialization.Model): - """Enable or disable encryption in transit. - - :ivar required: If encryption in transit is required. - :vartype required: bool - """ - - _attribute_map = { - "required": {"key": "Required", "type": "bool"}, - } - - def __init__(self, *, required: Optional[bool] = None, **kwargs: Any) -> None: - """ - :keyword required: If encryption in transit is required. - :paramtype required: bool - """ - super().__init__(**kwargs) - self.required = required - - -class ShareStats(_serialization.Model): - """Stats for the share. - - All required parameters must be populated in order to send to server. - - :ivar share_usage_bytes: The approximate size of the data stored in bytes. Note that this value - may not include all recently created or recently resized files. Required. - :vartype share_usage_bytes: int - """ - - _validation = { - "share_usage_bytes": {"required": True}, - } - - _attribute_map = { - "share_usage_bytes": {"key": "ShareUsageBytes", "type": "int"}, - } - - def __init__(self, *, share_usage_bytes: int, **kwargs: Any) -> None: - """ - :keyword share_usage_bytes: The approximate size of the data stored in bytes. Note that this - value may not include all recently created or recently resized files. Required. - :paramtype share_usage_bytes: int - """ - super().__init__(**kwargs) - self.share_usage_bytes = share_usage_bytes - - -class SignedIdentifier(_serialization.Model): - """Signed identifier. - - All required parameters must be populated in order to send to server. - - :ivar id: A unique id. Required. - :vartype id: str - :ivar access_policy: The access policy. - :vartype access_policy: ~azure.storage.fileshare.models.AccessPolicy - """ - - _validation = { - "id": {"required": True}, - } - - _attribute_map = { - "id": {"key": "Id", "type": "str"}, - "access_policy": {"key": "AccessPolicy", "type": "AccessPolicy"}, - } - - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - access_policy: Optional["_models.AccessPolicy"] = None, - **kwargs: Any - ) -> None: - """ - :keyword id: A unique id. Required. - :paramtype id: str - :keyword access_policy: The access policy. - :paramtype access_policy: ~azure.storage.fileshare.models.AccessPolicy - """ - super().__init__(**kwargs) - self.id = id - self.access_policy = access_policy - - -class SmbMultichannel(_serialization.Model): - """Settings for SMB multichannel. - - :ivar enabled: If SMB multichannel is enabled. - :vartype enabled: bool - """ - - _attribute_map = { - "enabled": {"key": "Enabled", "type": "bool"}, - } - _xml_map = {"name": "Multichannel"} - - def __init__(self, *, enabled: Optional[bool] = None, **kwargs: Any) -> None: - """ - :keyword enabled: If SMB multichannel is enabled. - :paramtype enabled: bool - """ - super().__init__(**kwargs) - self.enabled = enabled - - -class SourceLeaseAccessConditions(_serialization.Model): - """Parameter group. - - :ivar source_lease_id: Required if the source file has an active infinite lease. - :vartype source_lease_id: str - """ - - _attribute_map = { - "source_lease_id": {"key": "sourceLeaseId", "type": "str"}, - } - - def __init__(self, *, source_lease_id: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword source_lease_id: Required if the source file has an active infinite lease. - :paramtype source_lease_id: str - """ - super().__init__(**kwargs) - self.source_lease_id = source_lease_id - - -class SourceModifiedAccessConditions(_serialization.Model): - """Parameter group. - - :ivar source_if_match_crc64: Specify the crc64 value to operate only on range with a matching - crc64 checksum. - :vartype source_if_match_crc64: bytes - :ivar source_if_none_match_crc64: Specify the crc64 value to operate only on range without a - matching crc64 checksum. - :vartype source_if_none_match_crc64: bytes - """ - - _attribute_map = { - "source_if_match_crc64": {"key": "sourceIfMatchCrc64", "type": "bytearray"}, - "source_if_none_match_crc64": {"key": "sourceIfNoneMatchCrc64", "type": "bytearray"}, - } - - def __init__( - self, - *, - source_if_match_crc64: Optional[bytes] = None, - source_if_none_match_crc64: Optional[bytes] = None, - **kwargs: Any - ) -> None: - """ - :keyword source_if_match_crc64: Specify the crc64 value to operate only on range with a - matching crc64 checksum. - :paramtype source_if_match_crc64: bytes - :keyword source_if_none_match_crc64: Specify the crc64 value to operate only on range without a - matching crc64 checksum. - :paramtype source_if_none_match_crc64: bytes - """ - super().__init__(**kwargs) - self.source_if_match_crc64 = source_if_match_crc64 - self.source_if_none_match_crc64 = source_if_none_match_crc64 - - -class StorageError(_serialization.Model): - """StorageError. - - :ivar message: - :vartype message: str - :ivar copy_source_status_code: - :vartype copy_source_status_code: int - :ivar copy_source_error_code: - :vartype copy_source_error_code: str - :ivar copy_source_error_message: - :vartype copy_source_error_message: str - :ivar authentication_error_detail: - :vartype authentication_error_detail: str - """ - - _attribute_map = { - "message": {"key": "Message", "type": "str"}, - "copy_source_status_code": {"key": "CopySourceStatusCode", "type": "int"}, - "copy_source_error_code": {"key": "CopySourceErrorCode", "type": "str"}, - "copy_source_error_message": {"key": "CopySourceErrorMessage", "type": "str"}, - "authentication_error_detail": {"key": "AuthenticationErrorDetail", "type": "str"}, - } - - def __init__( - self, - *, - message: Optional[str] = None, - copy_source_status_code: Optional[int] = None, - copy_source_error_code: Optional[str] = None, - copy_source_error_message: Optional[str] = None, - authentication_error_detail: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword message: - :paramtype message: str - :keyword copy_source_status_code: - :paramtype copy_source_status_code: int - :keyword copy_source_error_code: - :paramtype copy_source_error_code: str - :keyword copy_source_error_message: - :paramtype copy_source_error_message: str - :keyword authentication_error_detail: - :paramtype authentication_error_detail: str - """ - super().__init__(**kwargs) - self.message = message - self.copy_source_status_code = copy_source_status_code - self.copy_source_error_code = copy_source_error_code - self.copy_source_error_message = copy_source_error_message - self.authentication_error_detail = authentication_error_detail - - -class StorageServiceProperties(_serialization.Model): - """Storage service properties. - - :ivar hour_metrics: A summary of request statistics grouped by API in hourly aggregates for - files. - :vartype hour_metrics: ~azure.storage.fileshare.models.Metrics - :ivar minute_metrics: A summary of request statistics grouped by API in minute aggregates for - files. - :vartype minute_metrics: ~azure.storage.fileshare.models.Metrics - :ivar cors: The set of CORS rules. - :vartype cors: list[~azure.storage.fileshare.models.CorsRule] - :ivar protocol: Protocol settings. - :vartype protocol: ~azure.storage.fileshare.models.ShareProtocolSettings - """ - - _attribute_map = { - "hour_metrics": {"key": "HourMetrics", "type": "Metrics"}, - "minute_metrics": {"key": "MinuteMetrics", "type": "Metrics"}, - "cors": {"key": "Cors", "type": "[CorsRule]", "xml": {"wrapped": True}}, - "protocol": {"key": "Protocol", "type": "ShareProtocolSettings"}, - } - - def __init__( - self, - *, - hour_metrics: Optional["_models.Metrics"] = None, - minute_metrics: Optional["_models.Metrics"] = None, - cors: Optional[list["_models.CorsRule"]] = None, - protocol: Optional["_models.ShareProtocolSettings"] = None, - **kwargs: Any - ) -> None: - """ - :keyword hour_metrics: A summary of request statistics grouped by API in hourly aggregates for - files. - :paramtype hour_metrics: ~azure.storage.fileshare.models.Metrics - :keyword minute_metrics: A summary of request statistics grouped by API in minute aggregates - for files. - :paramtype minute_metrics: ~azure.storage.fileshare.models.Metrics - :keyword cors: The set of CORS rules. - :paramtype cors: list[~azure.storage.fileshare.models.CorsRule] - :keyword protocol: Protocol settings. - :paramtype protocol: ~azure.storage.fileshare.models.ShareProtocolSettings - """ - super().__init__(**kwargs) - self.hour_metrics = hour_metrics - self.minute_metrics = minute_metrics - self.cors = cors - self.protocol = protocol - - -class StringEncoded(_serialization.Model): - """StringEncoded. - - :ivar encoded: - :vartype encoded: bool - :ivar content: - :vartype content: str - """ - - _attribute_map = { - "encoded": {"key": "Encoded", "type": "bool", "xml": {"name": "Encoded", "attr": True}}, - "content": {"key": "content", "type": "str", "xml": {"text": True}}, - } - - def __init__(self, *, encoded: Optional[bool] = None, content: Optional[str] = None, **kwargs: Any) -> None: - """ - :keyword encoded: - :paramtype encoded: bool - :keyword content: - :paramtype content: str - """ - super().__init__(**kwargs) - self.encoded = encoded - self.content = content - - -class UserDelegationKey(_serialization.Model): - """A user delegation key. - - All required parameters must be populated in order to send to server. - - :ivar signed_oid: The Azure Active Directory object ID in GUID format. Required. - :vartype signed_oid: str - :ivar signed_tid: The Azure Active Directory tenant ID in GUID format. Required. - :vartype signed_tid: str - :ivar signed_start: The date-time the key is active. Required. - :vartype signed_start: ~datetime.datetime - :ivar signed_expiry: The date-time the key expires. Required. - :vartype signed_expiry: ~datetime.datetime - :ivar signed_service: Abbreviation of the Azure Storage service that accepts the key. Required. - :vartype signed_service: str - :ivar signed_version: The service version that created the key. Required. - :vartype signed_version: str - :ivar signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if - DelegatedUserTid is specified. - :vartype signed_delegated_user_tid: str - :ivar value: The key as a base64 string. Required. - :vartype value: str - """ - - _validation = { - "signed_oid": {"required": True}, - "signed_tid": {"required": True}, - "signed_start": {"required": True}, - "signed_expiry": {"required": True}, - "signed_service": {"required": True}, - "signed_version": {"required": True}, - "value": {"required": True}, - } - - _attribute_map = { - "signed_oid": {"key": "SignedOid", "type": "str"}, - "signed_tid": {"key": "SignedTid", "type": "str"}, - "signed_start": {"key": "SignedStart", "type": "iso-8601"}, - "signed_expiry": {"key": "SignedExpiry", "type": "iso-8601"}, - "signed_service": {"key": "SignedService", "type": "str"}, - "signed_version": {"key": "SignedVersion", "type": "str"}, - "signed_delegated_user_tid": {"key": "SignedDelegatedUserTid", "type": "str"}, - "value": {"key": "Value", "type": "str"}, - } - - def __init__( - self, - *, - signed_oid: str, - signed_tid: str, - signed_start: datetime.datetime, - signed_expiry: datetime.datetime, - signed_service: str, - signed_version: str, - value: str, - signed_delegated_user_tid: Optional[str] = None, - **kwargs: Any - ) -> None: - """ - :keyword signed_oid: The Azure Active Directory object ID in GUID format. Required. - :paramtype signed_oid: str - :keyword signed_tid: The Azure Active Directory tenant ID in GUID format. Required. - :paramtype signed_tid: str - :keyword signed_start: The date-time the key is active. Required. - :paramtype signed_start: ~datetime.datetime - :keyword signed_expiry: The date-time the key expires. Required. - :paramtype signed_expiry: ~datetime.datetime - :keyword signed_service: Abbreviation of the Azure Storage service that accepts the key. - Required. - :paramtype signed_service: str - :keyword signed_version: The service version that created the key. Required. - :paramtype signed_version: str - :keyword signed_delegated_user_tid: The delegated user tenant id in Azure AD. Return if - DelegatedUserTid is specified. - :paramtype signed_delegated_user_tid: str - :keyword value: The key as a base64 string. Required. - :paramtype value: str - """ - super().__init__(**kwargs) - self.signed_oid = signed_oid - self.signed_tid = signed_tid - self.signed_start = signed_start - self.signed_expiry = signed_expiry - self.signed_service = signed_service - self.signed_version = signed_version - self.signed_delegated_user_tid = signed_delegated_user_tid - self.value = value diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_patch.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_patch.py index f7dd32510333..257980819201 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_patch.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_patch.py @@ -1,14 +1,275 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +import xml.etree.ElementTree as ET +from typing import Any, Callable, List, Optional -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField, _deserialize + + +def _patched_getattr(self, name): + """Lazily initialize _data for subclasses that skip super().__init__().""" + if name == "_data": + object.__setattr__(self, "_data", {}) + return self._data + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + +def _patched_setattr(self, name, value): + """Route attribute writes through _RestField descriptors even when shadowed.""" + if not name.startswith("_"): + try: + rf = type(self)._attr_to_rest_field.get(name) + except AttributeError: + pass + else: + if rf is not None: + rf.__set__(self, value) + return + object.__setattr__(self, name, value) + + +def _patched_getattribute(self, name): + """Route attribute reads through _RestField descriptors even when shadowed.""" + if not name.startswith("_"): + try: + rest_fields = type(self)._attr_to_rest_field + except AttributeError: + pass + else: + rf = rest_fields.get(name) + if rf is not None: + return rf.__get__(self, type(self)) + return object.__getattribute__(self, name) + + +# The original ``Model.__new__`` does ``rf._module = cls.__module__`` which +# lets an external subclass (e.g. from azure-storage-file-datalake) overwrite +# ``_module`` on the *shared* descriptor, corrupting type resolution for +# every class that shares it. This replacement resolves forward references +# against the module that *defined* the rest_field and uses that class's own +# annotations (not merged subclass annotations) to avoid resolving to a type +# whose ``__init__`` can't handle XML elements. + + +def _patched_new(cls, *args, **kwargs): + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # Walk only user-defined classes (base-first), stopping before the + # framework base. Each _RestField is configured with the module of + # the class that defined it so forward references resolve correctly. + user_classes = [] + for c in cls.__mro__: + if c is _Model: + break + user_classes.append(c) + + attr_to_rest_field: dict[str, _RestField] = {} + for mro_class in reversed(user_classes): + annotations = getattr(mro_class, "__annotations__", {}) + for k, v in mro_class.__dict__.items(): + if not k.startswith("_") and isinstance(v, _RestField): + attr_to_rest_field[k] = v + v._module = mro_class.__module__ + if not v._type: + v._type = v._get_deserialize_callable_from_annotation(annotations.get(k, None)) + if not v._rest_name_input: + v._rest_name_input = k + + cls._attr_to_rest_field = attr_to_rest_field + cls._backcompat_attr_to_rest_field = { + _Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf + for attr, rf in cls._attr_to_rest_field.items() + } + + # Reverse mapping: REST wire name → Python attribute name + cls._rest_name_to_attr = {rf._rest_name: attr for attr, rf in attr_to_rest_field.items()} + + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return object.__new__(cls) + + +_MyMutableMapping.__getattr__ = _patched_getattr +_MyMutableMapping.__setattr__ = _patched_setattr +_MyMutableMapping.__getattribute__ = _patched_getattribute +_Model.__new__ = _patched_new + + +# --------------------------------------------------------------------------- +# Backcompat shims for public methods that existed on the old autorest +# ``msrest.serialization.Model`` base class. The TypeSpec-generated models +# inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not +# expose ``serialize``/``deserialize``/``from_dict``/``validate``/ +# ``is_xml_model``/``enable_additional_properties_sending``. Re-adding them +# here preserves backward compatibility for users (e.g. azure-storage-file- +# datalake) that still call these methods on models re-exported from +# azure-storage-blob. +# --------------------------------------------------------------------------- + + +_original_as_dict = _Model.as_dict + + +def _remap_keys(d, rest_name_to_attr): + """Recursively remap REST wire-name keys to Python attribute names.""" + if isinstance(d, dict): + return {rest_name_to_attr.get(k, k): _remap_keys(v, rest_name_to_attr) for k, v in d.items()} + if isinstance(d, list): + return [_remap_keys(item, rest_name_to_attr) for item in d] + return d + + +def _patched_as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + *, + exclude_readonly: bool = False, + **kwargs: Any, +) -> dict: + """Backcompat wrapper that returns Python attribute names (snake_case). + + Accepts both the old autorest signature (``keep_readonly``, + ``key_transformer``) and the new TypeSpec keyword-only + ``exclude_readonly`` parameter. ``key_transformer`` is accepted for + signature compatibility but ignored; keys are always remapped to + Python attribute names. + """ + kwargs.pop("is_xml", None) + effective_exclude = exclude_readonly or not keep_readonly + result = _original_as_dict(self, exclude_readonly=effective_exclude) + rest_name_to_attr = getattr(type(self), "_rest_name_to_attr", {}) + return _remap_keys(result, rest_name_to_attr) + + +def _patched_serialize(self, keep_readonly: bool = False, **kwargs: Any) -> dict: + """Backcompat alias for the old autorest ``Model.serialize``. + + Equivalent to ``as_dict(keep_readonly=keep_readonly)`` with REST wire + names (camelCase) as keys — matching what the old autorest serializer + sent to the server. + """ + kwargs.pop("is_xml", None) + return _original_as_dict(self, exclude_readonly=not keep_readonly) + + +def _patched_validate(self) -> list: # pylint: disable=unused-argument + """Backcompat no-op for the old autorest ``Model.validate``. + + TypeSpec models do not perform client-side validation; return an empty + list to match the old "no errors" return value. + """ + return [] + + +def _patched_deserialize(cls, data: Any, content_type: Optional[str] = None) -> Any: + """Backcompat classmethod for the old autorest ``Model.deserialize``. + + Accepts either a JSON-compatible dict/str or (when ``content_type`` is + XML) an XML string or ``ElementTree.Element``. + """ + if content_type and "xml" in content_type.lower(): + if isinstance(data, (bytes, str)): + data = ET.fromstring(data) # nosec + return cls(data) + return _deserialize(cls, data) + + +def _patched_from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict, Any], Any]] = None, # pylint: disable=unused-argument + content_type: Optional[str] = None, +) -> Any: + """Backcompat classmethod for the old autorest ``Model.from_dict``. + + ``key_extractors`` is accepted for signature compatibility but ignored; + the TypeSpec deserializer always uses REST-key mapping. + """ + if content_type and "xml" in content_type.lower(): + if isinstance(data, (bytes, str)): + data = ET.fromstring(data) # nosec + return cls(data) + return _deserialize(cls, data) + + +def _patched_enable_additional_properties_sending(cls) -> None: # pylint: disable=unused-argument + """Backcompat no-op for the old autorest ``Model.enable_additional_properties_sending``. + + TypeSpec models already round-trip unknown properties through ``_data``. + """ + return None + + +def _patched_is_xml_model(cls) -> bool: + """Backcompat classmethod for the old autorest ``Model.is_xml_model``. + + Returns True when the model has an ``_xml`` class attribute (set by the + generator for models that serialize to/from XML). + """ + return bool(getattr(cls, "_xml", None)) + + +_Model.as_dict = _patched_as_dict +_Model.serialize = _patched_serialize +_Model.validate = _patched_validate +_Model.deserialize = classmethod(_patched_deserialize) +_Model.from_dict = classmethod(_patched_from_dict) +_Model.enable_additional_properties_sending = classmethod(_patched_enable_additional_properties_sending) +_Model.is_xml_model = classmethod(_patched_is_xml_model) + + +# --------------------------------------------------------------------------- +# Backcompat shim for legacy ``knack.util.todict`` consumers (e.g. Azure CLI). +# knack checks ``hasattr(obj, '_asdict')`` (namedtuple convention) BEFORE +# falling back to ``obj.__dict__``. TypeSpec ``_Model`` instances stash all +# fields in ``__dict__['_data']`` so a naive ``__dict__`` walk sees nothing. +# Returning the model contents with REST wire-name keys at every level +# matches what msrest models exposed when knack walked their ``__dict__`` +# and camelCased the snake_case attributes -- preserving the JSON shape the +# Azure CLI's ``_transformers.py`` expects. +# --------------------------------------------------------------------------- + + +def _asdict_value(v: Any) -> Any: + if v is None: + return None + if isinstance(v, _MyMutableMapping): + return _patched_namedtuple_asdict(v) + if isinstance(v, dict): + return {k: _asdict_value(val) for k, val in v.items()} + if isinstance(v, (list, tuple, set)): + return type(v)(_asdict_value(x) for x in v) + return v + + +def _patched_namedtuple_asdict(self) -> dict: + """Mirror msrest behaviour: include every declared field (REST wire + name) even when the value was never set, so legacy CLI consumers + that subscript by key (e.g. ``result['start']``) don't raise + ``KeyError`` for omitted optional fields.""" + result: dict = {} + rest_fields = getattr(type(self), "_attr_to_rest_field", None) or {} + data = getattr(self, "_data", {}) or {} + for rf in rest_fields.values(): + result[rf._rest_name] = _asdict_value(data.get(rf._rest_name)) + for k, v in data.items(): + if k not in result: + result[k] = _asdict_value(v) + return result + + +_Model._asdict = _patched_namedtuple_asdict + + +__all__: List[str] = [] def patch_sdk(): diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/__init__.py index 092b7efde334..9599ab012f5e 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/__init__.py @@ -2,7 +2,7 @@ # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. +# Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=wrong-import-position @@ -12,20 +12,20 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._service_operations import ServiceOperations # type: ignore -from ._share_operations import ShareOperations # type: ignore -from ._directory_operations import DirectoryOperations # type: ignore -from ._file_operations import FileOperations # type: ignore +from ._operations import DirectoryOperations # type: ignore +from ._operations import FileOperations # type: ignore +from ._operations import ServiceOperations # type: ignore +from ._operations import ShareOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "ServiceOperations", - "ShareOperations", "DirectoryOperations", "FileOperations", + "ServiceOperations", + "ShareOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_directory_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_directory_operations.py deleted file mode 100644 index 157426b206fe..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_directory_operations.py +++ /dev/null @@ -1,1596 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Literal, Optional, TypeVar, Union - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import AzureFileStorageConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_permission is not None: - _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") - if file_permission_format is not None: - _headers["x-ms-file-permission-format"] = _SERIALIZER.header( - "file_permission_format", file_permission_format, "str" - ) - if file_permission_key is not None: - _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") - if file_attributes is not None: - _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") - if file_creation_time is not None: - _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") - if file_last_write_time is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") - if file_change_time is not None: - _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if owner is not None: - _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") - if group is not None: - _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") - if file_mode is not None: - _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") - if file_property_semantics is not None: - _headers["x-ms-file-property-semantics"] = _SERIALIZER.header( - "file_property_semantics", file_property_semantics, "str" - ) - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_properties_request( - url: str, - *, - version: str, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_properties_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_permission is not None: - _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") - if file_permission_format is not None: - _headers["x-ms-file-permission-format"] = _SERIALIZER.header( - "file_permission_format", file_permission_format, "str" - ) - if file_permission_key is not None: - _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") - if file_attributes is not None: - _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") - if file_creation_time is not None: - _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") - if file_last_write_time is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") - if file_change_time is not None: - _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if owner is not None: - _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") - if group is not None: - _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") - if file_mode is not None: - _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_metadata_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_files_and_directories_segment_request( # pylint: disable=name-too-long - url: str, - *, - version: str, - prefix: Optional[str] = None, - sharesnapshot: Optional[str] = None, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - include: Optional[list[Union[str, _models.ListFilesIncludeType]]] = None, - include_extended_info: Optional[bool] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["list"] = kwargs.pop("comp", _params.pop("comp", "list")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if prefix is not None: - _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - if marker is not None: - _params["marker"] = _SERIALIZER.query("marker", marker, "str") - if maxresults is not None: - _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int", minimum=1) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if include is not None: - _params["include"] = _SERIALIZER.query("include", include, "[str]", div=",") - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if include_extended_info is not None: - _headers["x-ms-file-extended-info"] = _SERIALIZER.header("include_extended_info", include_extended_info, "bool") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_handles_request( - url: str, - *, - version: str, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - recursive: Optional[bool] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["listhandles"] = kwargs.pop("comp", _params.pop("comp", "listhandles")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if marker is not None: - _params["marker"] = _SERIALIZER.query("marker", marker, "str") - if maxresults is not None: - _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int", minimum=1) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - if recursive is not None: - _headers["x-ms-recursive"] = _SERIALIZER.header("recursive", recursive, "bool") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_force_close_handles_request( - url: str, - *, - handle_id: str, - version: str, - timeout: Optional[int] = None, - marker: Optional[str] = None, - sharesnapshot: Optional[str] = None, - recursive: Optional[bool] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["forceclosehandles"] = kwargs.pop("comp", _params.pop("comp", "forceclosehandles")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if marker is not None: - _params["marker"] = _SERIALIZER.query("marker", marker, "str") - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-handle-id"] = _SERIALIZER.header("handle_id", handle_id, "str") - if recursive is not None: - _headers["x-ms-recursive"] = _SERIALIZER.header("recursive", recursive, "bool") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_rename_request( # pylint: disable=too-many-locals - url: str, - *, - rename_source: str, - version: str, - timeout: Optional[int] = None, - replace_if_exists: Optional[bool] = None, - ignore_read_only: Optional[bool] = None, - source_lease_id: Optional[str] = None, - destination_lease_id: Optional[str] = None, - file_attributes: Optional[str] = None, - file_creation_time: Optional[str] = None, - file_last_write_time: Optional[str] = None, - file_change_time: Optional[str] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - allow_trailing_dot: Optional[bool] = None, - allow_source_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["rename"] = kwargs.pop("comp", _params.pop("comp", "rename")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["x-ms-file-rename-source"] = _SERIALIZER.header("rename_source", rename_source, "str") - if replace_if_exists is not None: - _headers["x-ms-file-rename-replace-if-exists"] = _SERIALIZER.header( - "replace_if_exists", replace_if_exists, "bool" - ) - if ignore_read_only is not None: - _headers["x-ms-file-rename-ignore-readonly"] = _SERIALIZER.header("ignore_read_only", ignore_read_only, "bool") - if source_lease_id is not None: - _headers["x-ms-source-lease-id"] = _SERIALIZER.header("source_lease_id", source_lease_id, "str") - if destination_lease_id is not None: - _headers["x-ms-destination-lease-id"] = _SERIALIZER.header("destination_lease_id", destination_lease_id, "str") - if file_attributes is not None: - _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") - if file_creation_time is not None: - _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") - if file_last_write_time is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") - if file_change_time is not None: - _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") - if file_permission is not None: - _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") - if file_permission_format is not None: - _headers["x-ms-file-permission-format"] = _SERIALIZER.header( - "file_permission_format", file_permission_format, "str" - ) - if file_permission_key is not None: - _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if allow_source_trailing_dot is not None: - _headers["x-ms-source-allow-trailing-dot"] = _SERIALIZER.header( - "allow_source_trailing_dot", allow_source_trailing_dot, "bool" - ) - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -class DirectoryOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare.AzureFileStorage`'s - :attr:`directory` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureFileStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def create( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - **kwargs: Any - ) -> None: - """Creates a new directory under the specified share or parent directory. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param file_attributes: If specified, the provided file attributes shall be set. Default value: - ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. - Default value is "none". - :type file_attributes: str - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param file_change_time: Change time for the file/directory. Default value: Now. Default value - is None. - :type file_change_time: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :param file_property_semantics: SMB only, default value is New. New will forcefully add the - ARCHIVE attribute flag and alter the permissions specified in x-ms-file-permission to inherit - missing permissions from the parent. Restore will apply changes without further modification. - Known values are: "New" and "Restore". Default value is None. - :type file_property_semantics: str or ~azure.storage.fileshare.models.FilePropertySemantics - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_create_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_attributes=file_attributes, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - file_change_time=file_change_time, - owner=owner, - group=group, - file_mode=file_mode, - file_property_semantics=file_property_semantics, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_properties( # pylint: disable=inconsistent-return-statements - self, sharesnapshot: Optional[str] = None, timeout: Optional[int] = None, **kwargs: Any - ) -> None: - """Returns all system properties for the specified directory, and can also be used to check the - existence of a directory. The data returned does not include the files in the directory or any - subdirectories. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_get_properties_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - timeout=timeout, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-server-encrypted") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, timeout: Optional[int] = None, **kwargs: Any - ) -> None: - """Removes the specified empty directory. Note that the directory must be empty before it can be - deleted. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_delete_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def set_properties( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - timeout: Optional[int] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - **kwargs: Any - ) -> None: - """Sets properties on the directory. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param file_attributes: If specified, the provided file attributes shall be set. Default value: - ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. - Default value is "none". - :type file_attributes: str - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param file_change_time: Change time for the file/directory. Default value: Now. Default value - is None. - :type file_change_time: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_set_properties_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_attributes=file_attributes, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - file_change_time=file_change_time, - owner=owner, - group=group, - file_mode=file_mode, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def set_metadata( # pylint: disable=inconsistent-return-statements - self, timeout: Optional[int] = None, metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> None: - """Updates user defined metadata for the specified directory. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_set_metadata_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def list_files_and_directories_segment( - self, - prefix: Optional[str] = None, - sharesnapshot: Optional[str] = None, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - include: Optional[list[Union[str, _models.ListFilesIncludeType]]] = None, - include_extended_info: Optional[bool] = None, - **kwargs: Any - ) -> _models.ListFilesAndDirectoriesSegmentResponse: - """Returns a list of files or directories under the specified share or directory. It lists the - contents only for a single level of the directory hierarchy. - - :param prefix: Filters the results to return only entries whose name begins with the specified - prefix. Default value is None. - :type prefix: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param maxresults: Specifies the maximum number of entries to return. If the request does not - specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 - items. Default value is None. - :type maxresults: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param include: Include this parameter to specify one or more datasets to include in the - response. Default value is None. - :type include: list[str or ~azure.storage.fileshare.models.ListFilesIncludeType] - :param include_extended_info: Include extended information. Default value is None. - :type include_extended_info: bool - :return: ListFilesAndDirectoriesSegmentResponse or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ListFilesAndDirectoriesSegmentResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["list"] = kwargs.pop("comp", _params.pop("comp", "list")) - cls: ClsType[_models.ListFilesAndDirectoriesSegmentResponse] = kwargs.pop("cls", None) - - _request = build_list_files_and_directories_segment_request( - url=self._config.url, - version=self._config.version, - prefix=prefix, - sharesnapshot=sharesnapshot, - marker=marker, - maxresults=maxresults, - timeout=timeout, - include=include, - include_extended_info=include_extended_info, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ListFilesAndDirectoriesSegmentResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_handles( - self, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - recursive: Optional[bool] = None, - **kwargs: Any - ) -> _models.ListHandlesResponse: - """Lists handles for directory. - - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param maxresults: Specifies the maximum number of entries to return. If the request does not - specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 - items. Default value is None. - :type maxresults: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param recursive: Specifies operation should apply to the directory specified in the URI, its - files, its subdirectories and their files. Default value is None. - :type recursive: bool - :return: ListHandlesResponse or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ListHandlesResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["listhandles"] = kwargs.pop("comp", _params.pop("comp", "listhandles")) - cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) - - _request = build_list_handles_request( - url=self._config.url, - version=self._config.version, - marker=marker, - maxresults=maxresults, - timeout=timeout, - sharesnapshot=sharesnapshot, - recursive=recursive, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ListHandlesResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def force_close_handles( # pylint: disable=inconsistent-return-statements - self, - handle_id: str, - timeout: Optional[int] = None, - marker: Optional[str] = None, - sharesnapshot: Optional[str] = None, - recursive: Optional[bool] = None, - **kwargs: Any - ) -> None: - """Closes all handles open for given directory. - - :param handle_id: Specifies handle ID opened on the file or directory to be closed. Asterisk - (‘*’) is a wildcard that specifies all handles. Required. - :type handle_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param recursive: Specifies operation should apply to the directory specified in the URI, its - files, its subdirectories and their files. Default value is None. - :type recursive: bool - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["forceclosehandles"] = kwargs.pop("comp", _params.pop("comp", "forceclosehandles")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_force_close_handles_request( - url=self._config.url, - handle_id=handle_id, - version=self._config.version, - timeout=timeout, - marker=marker, - sharesnapshot=sharesnapshot, - recursive=recursive, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-marker"] = self._deserialize("str", response.headers.get("x-ms-marker")) - response_headers["x-ms-number-of-handles-closed"] = self._deserialize( - "int", response.headers.get("x-ms-number-of-handles-closed") - ) - response_headers["x-ms-number-of-handles-failed"] = self._deserialize( - "int", response.headers.get("x-ms-number-of-handles-failed") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def rename( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - rename_source: str, - timeout: Optional[int] = None, - replace_if_exists: Optional[bool] = None, - ignore_read_only: Optional[bool] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - source_lease_access_conditions: Optional[_models.SourceLeaseAccessConditions] = None, - destination_lease_access_conditions: Optional[_models.DestinationLeaseAccessConditions] = None, - copy_file_smb_info: Optional[_models.CopyFileSmbInfo] = None, - **kwargs: Any - ) -> None: - """Renames a directory. - - :param rename_source: Required. Specifies the URI-style path of the source file, up to 2 KB in - length. Required. - :type rename_source: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param replace_if_exists: Optional. A boolean value for if the destination file already exists, - whether this request will overwrite the file or not. If true, the rename will succeed and will - overwrite the destination file. If not provided or if false and the destination file does - exist, the request will not overwrite the destination file. If provided and the destination - file doesn’t exist, the rename will succeed. Note: This value does not override the - x-ms-file-copy-ignore-read-only header value. Default value is None. - :type replace_if_exists: bool - :param ignore_read_only: Optional. A boolean value that specifies whether the ReadOnly - attribute on a preexisting destination file should be respected. If true, the rename will - succeed, otherwise, a previous file at the destination with the ReadOnly attribute set will - cause the rename to fail. Default value is None. - :type ignore_read_only: bool - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param source_lease_access_conditions: Parameter group. Default value is None. - :type source_lease_access_conditions: - ~azure.storage.fileshare.models.SourceLeaseAccessConditions - :param destination_lease_access_conditions: Parameter group. Default value is None. - :type destination_lease_access_conditions: - ~azure.storage.fileshare.models.DestinationLeaseAccessConditions - :param copy_file_smb_info: Parameter group. Default value is None. - :type copy_file_smb_info: ~azure.storage.fileshare.models.CopyFileSmbInfo - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["directory"] = kwargs.pop("restype", _params.pop("restype", "directory")) - comp: Literal["rename"] = kwargs.pop("comp", _params.pop("comp", "rename")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _source_lease_id = None - _destination_lease_id = None - _file_attributes = None - _file_creation_time = None - _file_last_write_time = None - _file_change_time = None - if source_lease_access_conditions is not None: - _source_lease_id = source_lease_access_conditions.source_lease_id - if destination_lease_access_conditions is not None: - _destination_lease_id = destination_lease_access_conditions.destination_lease_id - if copy_file_smb_info is not None: - _file_attributes = copy_file_smb_info.file_attributes - _file_change_time = copy_file_smb_info.file_change_time - _file_creation_time = copy_file_smb_info.file_creation_time - _file_last_write_time = copy_file_smb_info.file_last_write_time - - _request = build_rename_request( - url=self._config.url, - rename_source=rename_source, - version=self._config.version, - timeout=timeout, - replace_if_exists=replace_if_exists, - ignore_read_only=ignore_read_only, - source_lease_id=_source_lease_id, - destination_lease_id=_destination_lease_id, - file_attributes=_file_attributes, - file_creation_time=_file_creation_time, - file_last_write_time=_file_last_write_time, - file_change_time=_file_change_time, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - metadata=metadata, - allow_trailing_dot=self._config.allow_trailing_dot, - allow_source_trailing_dot=self._config.allow_source_trailing_dot, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_file_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_file_operations.py deleted file mode 100644 index 22ca6948e8b4..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_file_operations.py +++ /dev/null @@ -1,3865 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, IO, Iterator, Literal, Optional, TypeVar, Union - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import AzureFileStorageConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request( # pylint: disable=too-many-locals,too-many-statements,too-many-branches - url: str, - *, - file_content_length: int, - version: str, - timeout: Optional[int] = None, - file_content_type: Optional[str] = None, - file_content_encoding: Optional[str] = None, - file_content_language: Optional[str] = None, - file_cache_control: Optional[str] = None, - file_content_md5: Optional[bytes] = None, - file_content_disposition: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - lease_id: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, - content_md5: Optional[bytes] = None, - file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - content_length: Optional[int] = None, - structured_body_type: Optional[str] = None, - structured_content_length: Optional[int] = None, - content: Optional[IO[bytes]] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - file_type_constant: Literal["file"] = kwargs.pop("file_type_constant", _headers.pop("x-ms-type", "file")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["x-ms-content-length"] = _SERIALIZER.header("file_content_length", file_content_length, "int") - _headers["x-ms-type"] = _SERIALIZER.header("file_type_constant", file_type_constant, "str") - if file_content_type is not None: - _headers["x-ms-content-type"] = _SERIALIZER.header("file_content_type", file_content_type, "str") - if file_content_encoding is not None: - _headers["x-ms-content-encoding"] = _SERIALIZER.header("file_content_encoding", file_content_encoding, "str") - if file_content_language is not None: - _headers["x-ms-content-language"] = _SERIALIZER.header("file_content_language", file_content_language, "str") - if file_cache_control is not None: - _headers["x-ms-cache-control"] = _SERIALIZER.header("file_cache_control", file_cache_control, "str") - if file_content_md5 is not None: - _headers["x-ms-content-md5"] = _SERIALIZER.header("file_content_md5", file_content_md5, "bytearray") - if file_content_disposition is not None: - _headers["x-ms-content-disposition"] = _SERIALIZER.header( - "file_content_disposition", file_content_disposition, "str" - ) - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - if file_permission is not None: - _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") - if file_permission_format is not None: - _headers["x-ms-file-permission-format"] = _SERIALIZER.header( - "file_permission_format", file_permission_format, "str" - ) - if file_permission_key is not None: - _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") - if file_attributes is not None: - _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") - if file_creation_time is not None: - _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") - if file_last_write_time is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") - if file_change_time is not None: - _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if owner is not None: - _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") - if group is not None: - _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") - if file_mode is not None: - _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") - if nfs_file_type is not None: - _headers["x-ms-file-file-type"] = _SERIALIZER.header("nfs_file_type", nfs_file_type, "str") - if content_md5 is not None: - _headers["Content-MD5"] = _SERIALIZER.header("content_md5", content_md5, "bytearray") - if file_property_semantics is not None: - _headers["x-ms-file-property-semantics"] = _SERIALIZER.header( - "file_property_semantics", file_property_semantics, "str" - ) - if content_length is not None: - _headers["Content-Length"] = _SERIALIZER.header("content_length", content_length, "int") - if structured_body_type is not None: - _headers["x-ms-structured-body"] = _SERIALIZER.header("structured_body_type", structured_body_type, "str") - if structured_content_length is not None: - _headers["x-ms-structured-content-length"] = _SERIALIZER.header( - "structured_content_length", structured_content_length, "int" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_download_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - range: Optional[str] = None, - range_get_content_md5: Optional[bool] = None, - structured_body_type: Optional[str] = None, - lease_id: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if range is not None: - _headers["x-ms-range"] = _SERIALIZER.header("range", range, "str") - if range_get_content_md5 is not None: - _headers["x-ms-range-get-content-md5"] = _SERIALIZER.header( - "range_get_content_md5", range_get_content_md5, "bool" - ) - if structured_body_type is not None: - _headers["x-ms-structured-body"] = _SERIALIZER.header("structured_body_type", structured_body_type, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_properties_request( - url: str, - *, - version: str, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - lease_id: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - lease_id: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_http_headers_request( # pylint: disable=too-many-locals - url: str, - *, - version: str, - timeout: Optional[int] = None, - file_content_length: Optional[int] = None, - file_content_type: Optional[str] = None, - file_content_encoding: Optional[str] = None, - file_content_language: Optional[str] = None, - file_cache_control: Optional[str] = None, - file_content_md5: Optional[bytes] = None, - file_content_disposition: Optional[str] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - lease_id: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_content_length is not None: - _headers["x-ms-content-length"] = _SERIALIZER.header("file_content_length", file_content_length, "int") - if file_content_type is not None: - _headers["x-ms-content-type"] = _SERIALIZER.header("file_content_type", file_content_type, "str") - if file_content_encoding is not None: - _headers["x-ms-content-encoding"] = _SERIALIZER.header("file_content_encoding", file_content_encoding, "str") - if file_content_language is not None: - _headers["x-ms-content-language"] = _SERIALIZER.header("file_content_language", file_content_language, "str") - if file_cache_control is not None: - _headers["x-ms-cache-control"] = _SERIALIZER.header("file_cache_control", file_cache_control, "str") - if file_content_md5 is not None: - _headers["x-ms-content-md5"] = _SERIALIZER.header("file_content_md5", file_content_md5, "bytearray") - if file_content_disposition is not None: - _headers["x-ms-content-disposition"] = _SERIALIZER.header( - "file_content_disposition", file_content_disposition, "str" - ) - if file_permission is not None: - _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") - if file_permission_format is not None: - _headers["x-ms-file-permission-format"] = _SERIALIZER.header( - "file_permission_format", file_permission_format, "str" - ) - if file_permission_key is not None: - _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") - if file_attributes is not None: - _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") - if file_creation_time is not None: - _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") - if file_last_write_time is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") - if file_change_time is not None: - _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if owner is not None: - _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") - if group is not None: - _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") - if file_mode is not None: - _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_metadata_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - lease_id: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_acquire_lease_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - duration: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - request_id_parameter: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - if duration is not None: - _headers["x-ms-lease-duration"] = _SERIALIZER.header("duration", duration, "int") - if proposed_lease_id is not None: - _headers["x-ms-proposed-lease-id"] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_release_lease_request( - url: str, - *, - lease_id: str, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_change_lease_request( - url: str, - *, - lease_id: str, - version: str, - timeout: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - request_id_parameter: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if proposed_lease_id is not None: - _headers["x-ms-proposed-lease-id"] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_break_lease_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - lease_id: Optional[str] = None, - request_id_parameter: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_upload_range_request( - url: str, - *, - range: str, - content_length: int, - version: str, - timeout: Optional[int] = None, - file_range_write: Union[str, _models.FileRangeWriteType] = "update", - content_md5: Optional[bytes] = None, - lease_id: Optional[str] = None, - file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, - structured_body_type: Optional[str] = None, - structured_content_length: Optional[int] = None, - content: Optional[IO[bytes]] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["range"] = kwargs.pop("comp", _params.pop("comp", "range")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-range"] = _SERIALIZER.header("range", range, "str") - _headers["x-ms-write"] = _SERIALIZER.header("file_range_write", file_range_write, "str") - _headers["Content-Length"] = _SERIALIZER.header("content_length", content_length, "int") - if content_md5 is not None: - _headers["Content-MD5"] = _SERIALIZER.header("content_md5", content_md5, "bytearray") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_last_written_mode is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header( - "file_last_written_mode", file_last_written_mode, "str" - ) - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if structured_body_type is not None: - _headers["x-ms-structured-body"] = _SERIALIZER.header("structured_body_type", structured_body_type, "str") - if structured_content_length is not None: - _headers["x-ms-structured-content-length"] = _SERIALIZER.header( - "structured_content_length", structured_content_length, "int" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_upload_range_from_url_request( - url: str, - *, - range: str, - copy_source: str, - content_length: int, - version: str, - timeout: Optional[int] = None, - source_range: Optional[str] = None, - source_content_crc64: Optional[bytes] = None, - source_if_match_crc64: Optional[bytes] = None, - source_if_none_match_crc64: Optional[bytes] = None, - lease_id: Optional[str] = None, - copy_source_authorization: Optional[str] = None, - file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, - allow_trailing_dot: Optional[bool] = None, - allow_source_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["range"] = kwargs.pop("comp", _params.pop("comp", "range")) - file_range_write_from_url: Literal["update"] = kwargs.pop( - "file_range_write_from_url", _headers.pop("x-ms-write", "update") - ) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-range"] = _SERIALIZER.header("range", range, "str") - _headers["x-ms-copy-source"] = _SERIALIZER.header("copy_source", copy_source, "str") - if source_range is not None: - _headers["x-ms-source-range"] = _SERIALIZER.header("source_range", source_range, "str") - _headers["x-ms-write"] = _SERIALIZER.header("file_range_write_from_url", file_range_write_from_url, "str") - _headers["Content-Length"] = _SERIALIZER.header("content_length", content_length, "int") - if source_content_crc64 is not None: - _headers["x-ms-source-content-crc64"] = _SERIALIZER.header( - "source_content_crc64", source_content_crc64, "bytearray" - ) - if source_if_match_crc64 is not None: - _headers["x-ms-source-if-match-crc64"] = _SERIALIZER.header( - "source_if_match_crc64", source_if_match_crc64, "bytearray" - ) - if source_if_none_match_crc64 is not None: - _headers["x-ms-source-if-none-match-crc64"] = _SERIALIZER.header( - "source_if_none_match_crc64", source_if_none_match_crc64, "bytearray" - ) - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if copy_source_authorization is not None: - _headers["x-ms-copy-source-authorization"] = _SERIALIZER.header( - "copy_source_authorization", copy_source_authorization, "str" - ) - if file_last_written_mode is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header( - "file_last_written_mode", file_last_written_mode, "str" - ) - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if allow_source_trailing_dot is not None: - _headers["x-ms-source-allow-trailing-dot"] = _SERIALIZER.header( - "allow_source_trailing_dot", allow_source_trailing_dot, "bool" - ) - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_range_list_request( - url: str, - *, - version: str, - sharesnapshot: Optional[str] = None, - prevsharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - range: Optional[str] = None, - lease_id: Optional[str] = None, - support_rename: Optional[bool] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["rangelist"] = kwargs.pop("comp", _params.pop("comp", "rangelist")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - if prevsharesnapshot is not None: - _params["prevsharesnapshot"] = _SERIALIZER.query("prevsharesnapshot", prevsharesnapshot, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if range is not None: - _headers["x-ms-range"] = _SERIALIZER.header("range", range, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if support_rename is not None: - _headers["x-ms-file-support-rename"] = _SERIALIZER.header("support_rename", support_rename, "bool") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_start_copy_request( # pylint: disable=too-many-locals - url: str, - *, - copy_source: str, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_permission_copy_mode: Optional[Union[str, _models.PermissionCopyModeType]] = None, - ignore_read_only: Optional[bool] = None, - file_attributes: Optional[str] = None, - file_creation_time: Optional[str] = None, - file_last_write_time: Optional[str] = None, - file_change_time: Optional[str] = None, - set_archive_attribute: Optional[bool] = None, - lease_id: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - file_mode_copy_mode: Optional[Union[str, _models.ModeCopyMode]] = None, - file_owner_copy_mode: Optional[Union[str, _models.OwnerCopyMode]] = None, - allow_trailing_dot: Optional[bool] = None, - allow_source_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-copy-source"] = _SERIALIZER.header("copy_source", copy_source, "str") - if file_permission is not None: - _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") - if file_permission_format is not None: - _headers["x-ms-file-permission-format"] = _SERIALIZER.header( - "file_permission_format", file_permission_format, "str" - ) - if file_permission_key is not None: - _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") - if file_permission_copy_mode is not None: - _headers["x-ms-file-permission-copy-mode"] = _SERIALIZER.header( - "file_permission_copy_mode", file_permission_copy_mode, "str" - ) - if ignore_read_only is not None: - _headers["x-ms-file-copy-ignore-readonly"] = _SERIALIZER.header("ignore_read_only", ignore_read_only, "bool") - if file_attributes is not None: - _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") - if file_creation_time is not None: - _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") - if file_last_write_time is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") - if file_change_time is not None: - _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") - if set_archive_attribute is not None: - _headers["x-ms-file-copy-set-archive"] = _SERIALIZER.header( - "set_archive_attribute", set_archive_attribute, "bool" - ) - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if allow_source_trailing_dot is not None: - _headers["x-ms-source-allow-trailing-dot"] = _SERIALIZER.header( - "allow_source_trailing_dot", allow_source_trailing_dot, "bool" - ) - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if owner is not None: - _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") - if group is not None: - _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") - if file_mode is not None: - _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") - if file_mode_copy_mode is not None: - _headers["x-ms-file-mode-copy-mode"] = _SERIALIZER.header("file_mode_copy_mode", file_mode_copy_mode, "str") - if file_owner_copy_mode is not None: - _headers["x-ms-file-owner-copy-mode"] = _SERIALIZER.header("file_owner_copy_mode", file_owner_copy_mode, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_abort_copy_request( - url: str, - *, - copy_id: str, - version: str, - timeout: Optional[int] = None, - lease_id: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["copy"] = kwargs.pop("comp", _params.pop("comp", "copy")) - copy_action_abort_constant: Literal["abort"] = kwargs.pop( - "copy_action_abort_constant", _headers.pop("x-ms-copy-action", "abort") - ) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["copyid"] = _SERIALIZER.query("copy_id", copy_id, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-copy-action"] = _SERIALIZER.header("copy_action_abort_constant", copy_action_abort_constant, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_handles_request( - url: str, - *, - version: str, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["listhandles"] = kwargs.pop("comp", _params.pop("comp", "listhandles")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if marker is not None: - _params["marker"] = _SERIALIZER.query("marker", marker, "str") - if maxresults is not None: - _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int", minimum=1) - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_force_close_handles_request( - url: str, - *, - handle_id: str, - version: str, - timeout: Optional[int] = None, - marker: Optional[str] = None, - sharesnapshot: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["forceclosehandles"] = kwargs.pop("comp", _params.pop("comp", "forceclosehandles")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if marker is not None: - _params["marker"] = _SERIALIZER.query("marker", marker, "str") - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-handle-id"] = _SERIALIZER.header("handle_id", handle_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_rename_request( # pylint: disable=too-many-locals - url: str, - *, - rename_source: str, - version: str, - timeout: Optional[int] = None, - replace_if_exists: Optional[bool] = None, - ignore_read_only: Optional[bool] = None, - source_lease_id: Optional[str] = None, - destination_lease_id: Optional[str] = None, - file_attributes: Optional[str] = None, - file_creation_time: Optional[str] = None, - file_last_write_time: Optional[str] = None, - file_change_time: Optional[str] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - file_content_type: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, - allow_source_trailing_dot: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["rename"] = kwargs.pop("comp", _params.pop("comp", "rename")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["x-ms-file-rename-source"] = _SERIALIZER.header("rename_source", rename_source, "str") - if replace_if_exists is not None: - _headers["x-ms-file-rename-replace-if-exists"] = _SERIALIZER.header( - "replace_if_exists", replace_if_exists, "bool" - ) - if ignore_read_only is not None: - _headers["x-ms-file-rename-ignore-readonly"] = _SERIALIZER.header("ignore_read_only", ignore_read_only, "bool") - if source_lease_id is not None: - _headers["x-ms-source-lease-id"] = _SERIALIZER.header("source_lease_id", source_lease_id, "str") - if destination_lease_id is not None: - _headers["x-ms-destination-lease-id"] = _SERIALIZER.header("destination_lease_id", destination_lease_id, "str") - if file_attributes is not None: - _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") - if file_creation_time is not None: - _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") - if file_last_write_time is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") - if file_change_time is not None: - _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") - if file_permission is not None: - _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") - if file_permission_format is not None: - _headers["x-ms-file-permission-format"] = _SERIALIZER.header( - "file_permission_format", file_permission_format, "str" - ) - if file_permission_key is not None: - _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - if file_content_type is not None: - _headers["x-ms-content-type"] = _SERIALIZER.header("file_content_type", file_content_type, "str") - if allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") - if allow_source_trailing_dot is not None: - _headers["x-ms-source-allow-trailing-dot"] = _SERIALIZER.header( - "allow_source_trailing_dot", allow_source_trailing_dot, "bool" - ) - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_symbolic_link_request( - url: str, - *, - link_text: str, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_creation_time: str = "now", - file_last_write_time: str = "now", - request_id_parameter: Optional[str] = None, - lease_id: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["symboliclink"] = kwargs.pop("restype", _params.pop("restype", "symboliclink")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - if file_creation_time is not None: - _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") - if file_last_write_time is not None: - _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if owner is not None: - _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") - if group is not None: - _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") - _headers["x-ms-link-text"] = _SERIALIZER.header("link_text", link_text, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_symbolic_link_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["symboliclink"] = kwargs.pop("restype", _params.pop("restype", "symboliclink")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_hard_link_request( - url: str, - *, - target_file: str, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - lease_id: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["hardlink"] = kwargs.pop("restype", _params.pop("restype", "hardlink")) - file_type_constant: Literal["file"] = kwargs.pop("file_type_constant", _headers.pop("x-ms-type", "file")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["x-ms-type"] = _SERIALIZER.header("file_type_constant", file_type_constant, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - _headers["x-ms-file-target-file"] = _SERIALIZER.header("target_file", target_file, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -class FileOperations: # pylint: disable=too-many-public-methods - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare.AzureFileStorage`'s - :attr:`file` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureFileStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def create( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - file_content_length: int, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, - content_md5: Optional[bytes] = None, - file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - content_length: Optional[int] = None, - structured_body_type: Optional[str] = None, - structured_content_length: Optional[int] = None, - file_http_headers: Optional[_models.FileHTTPHeaders] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - optionalbody: Optional[IO[bytes]] = None, - **kwargs: Any - ) -> None: - """Creates a new file or replaces a file. Can also initialize the file with content. - - :param file_content_length: Specifies the maximum size for the file, up to 4 TB. Required. - :type file_content_length: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param file_attributes: If specified, the provided file attributes shall be set. Default value: - ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. - Default value is "none". - :type file_attributes: str - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param file_change_time: Change time for the file/directory. Default value: Now. Default value - is None. - :type file_change_time: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :param nfs_file_type: Optional, NFS only. Type of the file or directory. Known values are: - "Regular", "Directory", and "SymLink". Default value is None. - :type nfs_file_type: str or ~azure.storage.fileshare.models.NfsFileType - :param content_md5: An MD5 hash of the content. This hash is used to verify the integrity of - the data during transport. When the Content-MD5 header is specified, the File service compares - the hash of the content that has arrived with the header value that was sent. If the two hashes - do not match, the operation will fail with error code 400 (Bad Request). Default value is None. - :type content_md5: bytes - :param file_property_semantics: SMB only, default value is New. New will forcefully add the - ARCHIVE attribute flag and alter the permissions specified in x-ms-file-permission to inherit - missing permissions from the parent. Restore will apply changes without further modification. - Known values are: "New" and "Restore". Default value is None. - :type file_property_semantics: str or ~azure.storage.fileshare.models.FilePropertySemantics - :param content_length: Specifies the number of bytes being transmitted in the request body. - When the x-ms-write header is set to clear, the value of this header must be set to zero. - Default value is None. - :type content_length: int - :param structured_body_type: Required if the request body is a structured message. Specifies - the message schema version and properties. Default value is None. - :type structured_body_type: str - :param structured_content_length: Required if the request body is a structured message. - Specifies the length of the blob/file content inside the message body. Will always be smaller - than Content-Length. Default value is None. - :type structured_content_length: int - :param file_http_headers: Parameter group. Default value is None. - :type file_http_headers: ~azure.storage.fileshare.models.FileHTTPHeaders - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :param optionalbody: Initial data. Default value is None. - :type optionalbody: IO[bytes] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - file_type_constant: Literal["file"] = kwargs.pop("file_type_constant", _headers.pop("x-ms-type", "file")) - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/octet-stream") - ) - content_type = content_type if optionalbody else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _file_content_type = None - _file_content_encoding = None - _file_content_language = None - _file_cache_control = None - _file_content_md5 = None - _file_content_disposition = None - _lease_id = None - if file_http_headers is not None: - _file_cache_control = file_http_headers.file_cache_control - _file_content_disposition = file_http_headers.file_content_disposition - _file_content_encoding = file_http_headers.file_content_encoding - _file_content_language = file_http_headers.file_content_language - _file_content_md5 = file_http_headers.file_content_md5 - _file_content_type = file_http_headers.file_content_type - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - _content = optionalbody - - _request = build_create_request( - url=self._config.url, - file_content_length=file_content_length, - version=self._config.version, - timeout=timeout, - file_content_type=_file_content_type, - file_content_encoding=_file_content_encoding, - file_content_language=_file_content_language, - file_cache_control=_file_cache_control, - file_content_md5=_file_content_md5, - file_content_disposition=_file_content_disposition, - metadata=metadata, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_attributes=file_attributes, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - file_change_time=file_change_time, - lease_id=_lease_id, - owner=owner, - group=group, - file_mode=file_mode, - nfs_file_type=nfs_file_type, - content_md5=content_md5, - file_property_semantics=file_property_semantics, - content_length=content_length, - structured_body_type=structured_body_type, - structured_content_length=structured_content_length, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - file_type_constant=file_type_constant, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) - response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) - response_headers["x-ms-structured-body"] = self._deserialize( - "str", response.headers.get("x-ms-structured-body") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def download( - self, - timeout: Optional[int] = None, - range: Optional[str] = None, - range_get_content_md5: Optional[bool] = None, - structured_body_type: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> Iterator[bytes]: - """Reads or downloads a file from the system, including its metadata and properties. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param range: Return file data only from the specified byte range. Default value is None. - :type range: str - :param range_get_content_md5: When this header is set to true and specified together with the - Range header, the service returns the MD5 hash for the range, as long as the range is less than - or equal to 4 MB in size. Default value is None. - :type range_get_content_md5: bool - :param structured_body_type: Specifies the response content should be returned as a structured - message and specifies the message schema version and properties. Default value is None. - :type structured_body_type: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: Iterator[bytes] or the result of cls(response) - :rtype: Iterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_download_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - range=range, - range_get_content_md5=range_get_content_md5, - structured_body_type=structured_body_type, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 206]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) - response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["Content-Range"] = self._deserialize("str", response.headers.get("Content-Range")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) - response_headers["Content-Encoding"] = self._deserialize("str", response.headers.get("Content-Encoding")) - response_headers["Cache-Control"] = self._deserialize("str", response.headers.get("Cache-Control")) - response_headers["Content-Disposition"] = self._deserialize("str", response.headers.get("Content-Disposition")) - response_headers["Content-Language"] = self._deserialize("str", response.headers.get("Content-Language")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Accept-Ranges"] = self._deserialize("str", response.headers.get("Accept-Ranges")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-copy-completion-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-copy-completion-time") - ) - response_headers["x-ms-copy-status-description"] = self._deserialize( - "str", response.headers.get("x-ms-copy-status-description") - ) - response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) - response_headers["x-ms-copy-progress"] = self._deserialize("str", response.headers.get("x-ms-copy-progress")) - response_headers["x-ms-copy-source"] = self._deserialize("str", response.headers.get("x-ms-copy-source")) - response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) - response_headers["x-ms-content-md5"] = self._deserialize("bytearray", response.headers.get("x-ms-content-md5")) - response_headers["x-ms-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-server-encrypted") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) - response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) - response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) - response_headers["x-ms-structured-body"] = self._deserialize( - "str", response.headers.get("x-ms-structured-body") - ) - response_headers["x-ms-structured-content-length"] = self._deserialize( - "int", response.headers.get("x-ms-structured-content-length") - ) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - - deserialized = response.stream_download(self._client._pipeline, decompress=_decompress) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_properties( # pylint: disable=inconsistent-return-statements - self, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Returns all user-defined metadata, standard HTTP properties, and system properties for the - file. It does not return the content of the file. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_properties_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - timeout=timeout, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) - response_headers["x-ms-type"] = self._deserialize("str", response.headers.get("x-ms-type")) - response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) - response_headers["Content-Encoding"] = self._deserialize("str", response.headers.get("Content-Encoding")) - response_headers["Cache-Control"] = self._deserialize("str", response.headers.get("Cache-Control")) - response_headers["Content-Disposition"] = self._deserialize("str", response.headers.get("Content-Disposition")) - response_headers["Content-Language"] = self._deserialize("str", response.headers.get("Content-Language")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-copy-completion-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-copy-completion-time") - ) - response_headers["x-ms-copy-status-description"] = self._deserialize( - "str", response.headers.get("x-ms-copy-status-description") - ) - response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) - response_headers["x-ms-copy-progress"] = self._deserialize("str", response.headers.get("x-ms-copy-progress")) - response_headers["x-ms-copy-source"] = self._deserialize("str", response.headers.get("x-ms-copy-source")) - response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) - response_headers["x-ms-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-server-encrypted") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) - response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) - response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """removes the file from the storage account. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_delete_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - timeout: Optional[int] = None, - file_content_length: Optional[int] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - file_attributes: str = "none", - file_creation_time: str = "now", - file_last_write_time: str = "now", - file_change_time: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - file_http_headers: Optional[_models.FileHTTPHeaders] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Sets HTTP headers on the file. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param file_content_length: Resizes a file to the specified size. If the specified byte value - is less than the current size of the file, then all ranges above the specified byte value are - cleared. Default value is None. - :type file_content_length: int - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param file_attributes: If specified, the provided file attributes shall be set. Default value: - ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. - Default value is "none". - :type file_attributes: str - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param file_change_time: Change time for the file/directory. Default value: Now. Default value - is None. - :type file_change_time: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :param file_http_headers: Parameter group. Default value is None. - :type file_http_headers: ~azure.storage.fileshare.models.FileHTTPHeaders - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _file_content_type = None - _file_content_encoding = None - _file_content_language = None - _file_cache_control = None - _file_content_md5 = None - _file_content_disposition = None - _lease_id = None - if file_http_headers is not None: - _file_cache_control = file_http_headers.file_cache_control - _file_content_disposition = file_http_headers.file_content_disposition - _file_content_encoding = file_http_headers.file_content_encoding - _file_content_language = file_http_headers.file_content_language - _file_content_md5 = file_http_headers.file_content_md5 - _file_content_type = file_http_headers.file_content_type - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_set_http_headers_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_content_length=file_content_length, - file_content_type=_file_content_type, - file_content_encoding=_file_content_encoding, - file_content_language=_file_content_language, - file_cache_control=_file_cache_control, - file_content_md5=_file_content_md5, - file_content_disposition=_file_content_disposition, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_attributes=file_attributes, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - file_change_time=file_change_time, - lease_id=_lease_id, - owner=owner, - group=group, - file_mode=file_mode, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def set_metadata( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Updates user-defined metadata for the specified file. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_set_metadata_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def acquire_lease( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - duration: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """[Update] The Lease File operation establishes and manages a lock on a file for write and delete - operations. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param duration: Specifies the duration of the lease, in seconds, or negative one (-1) for a - lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease - duration cannot be changed using renew or change. Default value is None. - :type duration: int - :param proposed_lease_id: Proposed lease ID, in a GUID string format. The File service returns - 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid - Constructor (String) for a list of valid GUID string formats. Default value is None. - :type proposed_lease_id: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_acquire_lease_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - duration=duration, - proposed_lease_id=proposed_lease_id, - request_id_parameter=request_id_parameter, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def release_lease( # pylint: disable=inconsistent-return-statements - self, lease_id: str, timeout: Optional[int] = None, request_id_parameter: Optional[str] = None, **kwargs: Any - ) -> None: - """[Update] The Lease File operation establishes and manages a lock on a file for write and delete - operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_release_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - request_id_parameter=request_id_parameter, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def change_lease( # pylint: disable=inconsistent-return-statements - self, - lease_id: str, - timeout: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """[Update] The Lease File operation establishes and manages a lock on a file for write and delete - operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param proposed_lease_id: Proposed lease ID, in a GUID string format. The File service returns - 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid - Constructor (String) for a list of valid GUID string formats. Default value is None. - :type proposed_lease_id: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_change_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - proposed_lease_id=proposed_lease_id, - request_id_parameter=request_id_parameter, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def break_lease( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """[Update] The Lease File operation establishes and manages a lock on a file for write and delete - operations. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_break_lease_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - request_id_parameter=request_id_parameter, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def upload_range( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - range: str, - content_length: int, - timeout: Optional[int] = None, - file_range_write: Union[str, _models.FileRangeWriteType] = "update", - content_md5: Optional[bytes] = None, - file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, - structured_body_type: Optional[str] = None, - structured_content_length: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - optionalbody: Optional[IO[bytes]] = None, - **kwargs: Any - ) -> None: - """Upload a range of bytes to a file. - - :param range: Specifies the range of bytes to be written. Both the start and end of the range - must be specified. For an update operation, the range can be up to 4 MB in size. For a clear - operation, the range can be up to the value of the file's full size. The File service accepts - only a single byte range for the Range and 'x-ms-range' headers, and the byte range must be - specified in the following format: bytes=startByte-endByte. Required. - :type range: str - :param content_length: Specifies the number of bytes being transmitted in the request body. - When the x-ms-write header is set to clear, the value of this header must be set to zero. - Required. - :type content_length: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param file_range_write: Specify one of the following options: - Update: Writes the bytes - specified by the request body into the specified range. The Range and Content-Length headers - must match to perform the update. - Clear: Clears the specified range and releases the space - used in storage for that range. To clear a range, set the Content-Length header to zero, and - set the Range header to a value that indicates the range to clear, up to maximum file size. - Known values are: "update" and "clear". Default value is "update". - :type file_range_write: str or ~azure.storage.fileshare.models.FileRangeWriteType - :param content_md5: An MD5 hash of the content. This hash is used to verify the integrity of - the data during transport. When the Content-MD5 header is specified, the File service compares - the hash of the content that has arrived with the header value that was sent. If the two hashes - do not match, the operation will fail with error code 400 (Bad Request). Default value is None. - :type content_md5: bytes - :param file_last_written_mode: If the file last write time should be preserved or overwritten. - Known values are: "Now" and "Preserve". Default value is None. - :type file_last_written_mode: str or ~azure.storage.fileshare.models.FileLastWrittenMode - :param structured_body_type: Required if the request body is a structured message. Specifies - the message schema version and properties. Default value is None. - :type structured_body_type: str - :param structured_content_length: Required if the request body is a structured message. - Specifies the length of the blob/file content inside the message body. Will always be smaller - than Content-Length. Default value is None. - :type structured_content_length: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :param optionalbody: Initial data. Default value is None. - :type optionalbody: IO[bytes] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["range"] = kwargs.pop("comp", _params.pop("comp", "range")) - content_type: Optional[str] = kwargs.pop( - "content_type", _headers.pop("Content-Type", "application/octet-stream") - ) - content_type = content_type if optionalbody else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - _content = optionalbody - - _request = build_upload_range_request( - url=self._config.url, - range=range, - content_length=content_length, - version=self._config.version, - timeout=timeout, - file_range_write=file_range_write, - content_md5=content_md5, - lease_id=_lease_id, - file_last_written_mode=file_last_written_mode, - structured_body_type=structured_body_type, - structured_content_length=structured_content_length, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-structured-body"] = self._deserialize( - "str", response.headers.get("x-ms-structured-body") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def upload_range_from_url( # pylint: disable=inconsistent-return-statements - self, - range: str, - copy_source: str, - content_length: int, - timeout: Optional[int] = None, - source_range: Optional[str] = None, - source_content_crc64: Optional[bytes] = None, - copy_source_authorization: Optional[str] = None, - file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, - source_modified_access_conditions: Optional[_models.SourceModifiedAccessConditions] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Upload a range of bytes to a file where the contents are read from a URL. - - :param range: Writes data to the specified byte range in the file. Required. - :type range: str - :param copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. To copy - a file to another file within the same storage account, you may use Shared Key to authenticate - the source file. If you are copying a file from another storage account, or if you are copying - a blob from the same storage account or another storage account, then you must authenticate the - source file or blob using a shared access signature. If the source is a public blob, no - authentication is required to perform the copy operation. A file in a share snapshot can also - be specified as a copy source. Required. - :type copy_source: str - :param content_length: Specifies the number of bytes being transmitted in the request body. - When the x-ms-write header is set to clear, the value of this header must be set to zero. - Required. - :type content_length: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param source_range: Bytes of source data in the specified range. Default value is None. - :type source_range: str - :param source_content_crc64: Specify the crc64 calculated for the range of bytes that must be - read from the copy source. Default value is None. - :type source_content_crc64: bytes - :param copy_source_authorization: Only Bearer type is supported. Credentials should be a valid - OAuth access token to copy source. Default value is None. - :type copy_source_authorization: str - :param file_last_written_mode: If the file last write time should be preserved or overwritten. - Known values are: "Now" and "Preserve". Default value is None. - :type file_last_written_mode: str or ~azure.storage.fileshare.models.FileLastWrittenMode - :param source_modified_access_conditions: Parameter group. Default value is None. - :type source_modified_access_conditions: - ~azure.storage.fileshare.models.SourceModifiedAccessConditions - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["range"] = kwargs.pop("comp", _params.pop("comp", "range")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _source_if_match_crc64 = None - _source_if_none_match_crc64 = None - _lease_id = None - if source_modified_access_conditions is not None: - _source_if_match_crc64 = source_modified_access_conditions.source_if_match_crc64 - _source_if_none_match_crc64 = source_modified_access_conditions.source_if_none_match_crc64 - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_upload_range_from_url_request( - url=self._config.url, - range=range, - copy_source=copy_source, - content_length=content_length, - version=self._config.version, - timeout=timeout, - source_range=source_range, - source_content_crc64=source_content_crc64, - source_if_match_crc64=_source_if_match_crc64, - source_if_none_match_crc64=_source_if_none_match_crc64, - lease_id=_lease_id, - copy_source_authorization=copy_source_authorization, - file_last_written_mode=file_last_written_mode, - allow_trailing_dot=self._config.allow_trailing_dot, - allow_source_trailing_dot=self._config.allow_source_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - file_range_write_from_url=self._config.file_range_write_from_url, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-content-crc64"] = self._deserialize( - "bytearray", response.headers.get("x-ms-content-crc64") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_range_list( - self, - sharesnapshot: Optional[str] = None, - prevsharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - range: Optional[str] = None, - support_rename: Optional[bool] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> _models.ShareFileRangeList: - """Returns the list of valid ranges for a file. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param prevsharesnapshot: The previous snapshot parameter is an opaque DateTime value that, - when present, specifies the previous snapshot. Default value is None. - :type prevsharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param range: Specifies the range of bytes over which to list ranges, inclusively. Default - value is None. - :type range: str - :param support_rename: This header is allowed only when PrevShareSnapshot query parameter is - set. Determines whether the changed ranges for a file that has been renamed or moved between - the target snapshot (or the live file) and the previous snapshot should be listed. If the value - is true, the valid changed ranges for the file will be returned. If the value is false, the - operation will result in a failure with 409 (Conflict) response. The default value is false. - Default value is None. - :type support_rename: bool - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: ShareFileRangeList or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ShareFileRangeList - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["rangelist"] = kwargs.pop("comp", _params.pop("comp", "rangelist")) - cls: ClsType[_models.ShareFileRangeList] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_range_list_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - prevsharesnapshot=prevsharesnapshot, - timeout=timeout, - range=range, - lease_id=_lease_id, - support_rename=support_rename, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["x-ms-content-length"] = self._deserialize("int", response.headers.get("x-ms-content-length")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ShareFileRangeList", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def start_copy( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - copy_source: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = None, - file_mode_copy_mode: Optional[Union[str, _models.ModeCopyMode]] = None, - file_owner_copy_mode: Optional[Union[str, _models.OwnerCopyMode]] = None, - copy_file_smb_info: Optional[_models.CopyFileSmbInfo] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Copies a blob or file to a destination file within the storage account. - - :param copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. To copy - a file to another file within the same storage account, you may use Shared Key to authenticate - the source file. If you are copying a file from another storage account, or if you are copying - a blob from the same storage account or another storage account, then you must authenticate the - source file or blob using a shared access signature. If the source is a public blob, no - authentication is required to perform the copy operation. A file in a share snapshot can also - be specified as a copy source. Required. - :type copy_source: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param file_mode: Optional, NFS only. The file mode of the file or directory. Default value is - None. - :type file_mode: str - :param file_mode_copy_mode: NFS only. Applicable only when the copy source is a File. - Determines the copy behavior of the mode bits of the file. source: The mode on the destination - file is copied from the source file. override: The mode on the destination file is determined - via the x-ms-mode header. Known values are: "source" and "override". Default value is None. - :type file_mode_copy_mode: str or ~azure.storage.fileshare.models.ModeCopyMode - :param file_owner_copy_mode: NFS only. Determines the copy behavior of the owner user - identifier (UID) and group identifier (GID) of the file. source: The owner user identifier - (UID) and group identifier (GID) on the destination file is copied from the source file. - override: The owner user identifier (UID) and group identifier (GID) on the destination file is - determined via the x-ms-owner and x-ms-group headers. Known values are: "source" and - "override". Default value is None. - :type file_owner_copy_mode: str or ~azure.storage.fileshare.models.OwnerCopyMode - :param copy_file_smb_info: Parameter group. Default value is None. - :type copy_file_smb_info: ~azure.storage.fileshare.models.CopyFileSmbInfo - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[None] = kwargs.pop("cls", None) - - _file_permission_copy_mode = None - _ignore_read_only = None - _file_attributes = None - _file_creation_time = None - _file_last_write_time = None - _file_change_time = None - _set_archive_attribute = None - _lease_id = None - if copy_file_smb_info is not None: - _file_attributes = copy_file_smb_info.file_attributes - _file_change_time = copy_file_smb_info.file_change_time - _file_creation_time = copy_file_smb_info.file_creation_time - _file_last_write_time = copy_file_smb_info.file_last_write_time - _file_permission_copy_mode = copy_file_smb_info.file_permission_copy_mode - _ignore_read_only = copy_file_smb_info.ignore_read_only - _set_archive_attribute = copy_file_smb_info.set_archive_attribute - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_start_copy_request( - url=self._config.url, - copy_source=copy_source, - version=self._config.version, - timeout=timeout, - metadata=metadata, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - file_permission_copy_mode=_file_permission_copy_mode, - ignore_read_only=_ignore_read_only, - file_attributes=_file_attributes, - file_creation_time=_file_creation_time, - file_last_write_time=_file_last_write_time, - file_change_time=_file_change_time, - set_archive_attribute=_set_archive_attribute, - lease_id=_lease_id, - owner=owner, - group=group, - file_mode=file_mode, - file_mode_copy_mode=file_mode_copy_mode, - file_owner_copy_mode=file_owner_copy_mode, - allow_trailing_dot=self._config.allow_trailing_dot, - allow_source_trailing_dot=self._config.allow_source_trailing_dot, - file_request_intent=self._config.file_request_intent, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) - response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def abort_copy( # pylint: disable=inconsistent-return-statements - self, - copy_id: str, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Aborts a pending Copy File operation, and leaves a destination file with zero length and full - metadata. - - :param copy_id: The copy identifier provided in the x-ms-copy-id header of the original Copy - File operation. Required. - :type copy_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["copy"] = kwargs.pop("comp", _params.pop("comp", "copy")) - copy_action_abort_constant: Literal["abort"] = kwargs.pop( - "copy_action_abort_constant", _headers.pop("x-ms-copy-action", "abort") - ) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_abort_copy_request( - url=self._config.url, - copy_id=copy_id, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - copy_action_abort_constant=copy_action_abort_constant, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def list_handles( - self, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - **kwargs: Any - ) -> _models.ListHandlesResponse: - """Lists handles for file. - - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param maxresults: Specifies the maximum number of entries to return. If the request does not - specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 - items. Default value is None. - :type maxresults: int - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :return: ListHandlesResponse or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ListHandlesResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["listhandles"] = kwargs.pop("comp", _params.pop("comp", "listhandles")) - cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) - - _request = build_list_handles_request( - url=self._config.url, - version=self._config.version, - marker=marker, - maxresults=maxresults, - timeout=timeout, - sharesnapshot=sharesnapshot, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ListHandlesResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def force_close_handles( # pylint: disable=inconsistent-return-statements - self, - handle_id: str, - timeout: Optional[int] = None, - marker: Optional[str] = None, - sharesnapshot: Optional[str] = None, - **kwargs: Any - ) -> None: - """Closes all handles open for given file. - - :param handle_id: Specifies handle ID opened on the file or directory to be closed. Asterisk - (‘*’) is a wildcard that specifies all handles. Required. - :type handle_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["forceclosehandles"] = kwargs.pop("comp", _params.pop("comp", "forceclosehandles")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_force_close_handles_request( - url=self._config.url, - handle_id=handle_id, - version=self._config.version, - timeout=timeout, - marker=marker, - sharesnapshot=sharesnapshot, - allow_trailing_dot=self._config.allow_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-marker"] = self._deserialize("str", response.headers.get("x-ms-marker")) - response_headers["x-ms-number-of-handles-closed"] = self._deserialize( - "int", response.headers.get("x-ms-number-of-handles-closed") - ) - response_headers["x-ms-number-of-handles-failed"] = self._deserialize( - "int", response.headers.get("x-ms-number-of-handles-failed") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def rename( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - rename_source: str, - timeout: Optional[int] = None, - replace_if_exists: Optional[bool] = None, - ignore_read_only: Optional[bool] = None, - file_permission: str = "inherit", - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - file_permission_key: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - source_lease_access_conditions: Optional[_models.SourceLeaseAccessConditions] = None, - destination_lease_access_conditions: Optional[_models.DestinationLeaseAccessConditions] = None, - copy_file_smb_info: Optional[_models.CopyFileSmbInfo] = None, - file_http_headers: Optional[_models.FileHTTPHeaders] = None, - **kwargs: Any - ) -> None: - """Renames a file. - - :param rename_source: Required. Specifies the URI-style path of the source file, up to 2 KB in - length. Required. - :type rename_source: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param replace_if_exists: Optional. A boolean value for if the destination file already exists, - whether this request will overwrite the file or not. If true, the rename will succeed and will - overwrite the destination file. If not provided or if false and the destination file does - exist, the request will not overwrite the destination file. If provided and the destination - file doesn’t exist, the rename will succeed. Note: This value does not override the - x-ms-file-copy-ignore-read-only header value. Default value is None. - :type replace_if_exists: bool - :param ignore_read_only: Optional. A boolean value that specifies whether the ReadOnly - attribute on a preexisting destination file should be respected. If true, the rename will - succeed, otherwise, a previous file at the destination with the ReadOnly attribute set will - cause the rename to fail. Default value is None. - :type ignore_read_only: bool - :param file_permission: If specified the permission (security descriptor) shall be set for the - directory/file. This header can be used if Permission size is <= 8KB, else - x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as - input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or - x-ms-file-permission-key should be specified. Default value is "inherit". - :type file_permission: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param file_permission_key: Key of the permission to be set for the directory/file. Note: Only - one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default value - is None. - :type file_permission_key: str - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param source_lease_access_conditions: Parameter group. Default value is None. - :type source_lease_access_conditions: - ~azure.storage.fileshare.models.SourceLeaseAccessConditions - :param destination_lease_access_conditions: Parameter group. Default value is None. - :type destination_lease_access_conditions: - ~azure.storage.fileshare.models.DestinationLeaseAccessConditions - :param copy_file_smb_info: Parameter group. Default value is None. - :type copy_file_smb_info: ~azure.storage.fileshare.models.CopyFileSmbInfo - :param file_http_headers: Parameter group. Default value is None. - :type file_http_headers: ~azure.storage.fileshare.models.FileHTTPHeaders - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["rename"] = kwargs.pop("comp", _params.pop("comp", "rename")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _source_lease_id = None - _destination_lease_id = None - _file_attributes = None - _file_creation_time = None - _file_last_write_time = None - _file_change_time = None - _file_content_type = None - if source_lease_access_conditions is not None: - _source_lease_id = source_lease_access_conditions.source_lease_id - if destination_lease_access_conditions is not None: - _destination_lease_id = destination_lease_access_conditions.destination_lease_id - if copy_file_smb_info is not None: - _file_attributes = copy_file_smb_info.file_attributes - _file_change_time = copy_file_smb_info.file_change_time - _file_creation_time = copy_file_smb_info.file_creation_time - _file_last_write_time = copy_file_smb_info.file_last_write_time - if file_http_headers is not None: - _file_content_type = file_http_headers.file_content_type - - _request = build_rename_request( - url=self._config.url, - rename_source=rename_source, - version=self._config.version, - timeout=timeout, - replace_if_exists=replace_if_exists, - ignore_read_only=ignore_read_only, - source_lease_id=_source_lease_id, - destination_lease_id=_destination_lease_id, - file_attributes=_file_attributes, - file_creation_time=_file_creation_time, - file_last_write_time=_file_last_write_time, - file_change_time=_file_change_time, - file_permission=file_permission, - file_permission_format=file_permission_format, - file_permission_key=file_permission_key, - metadata=metadata, - file_content_type=_file_content_type, - allow_trailing_dot=self._config.allow_trailing_dot, - allow_source_trailing_dot=self._config.allow_source_trailing_dot, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-request-server-encrypted"] = self._deserialize( - "bool", response.headers.get("x-ms-request-server-encrypted") - ) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - response_headers["x-ms-file-attributes"] = self._deserialize( - "str", response.headers.get("x-ms-file-attributes") - ) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def create_symbolic_link( # pylint: disable=inconsistent-return-statements - self, - link_text: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_creation_time: str = "now", - file_last_write_time: str = "now", - request_id_parameter: Optional[str] = None, - owner: Optional[str] = None, - group: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Creates a symbolic link. - - :param link_text: NFS only. Required. The path to the original file, the symbolic link is - pointing to. The path is of type string which is not resolved and is stored as is. The path can - be absolute path or the relative path depending on the content stored in the symbolic link - file. Required. - :type link_text: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param file_creation_time: Creation time for the file/directory. Default value: Now. Default - value is "now". - :type file_creation_time: str - :param file_last_write_time: Last write time for the file/directory. Default value: Now. - Default value is "now". - :type file_last_write_time: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param owner: Optional, NFS only. The owner of the file or directory. Default value is None. - :type owner: str - :param group: Optional, NFS only. The owning group of the file or directory. Default value is - None. - :type group: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["symboliclink"] = kwargs.pop("restype", _params.pop("restype", "symboliclink")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_create_symbolic_link_request( - url=self._config.url, - link_text=link_text, - version=self._config.version, - timeout=timeout, - metadata=metadata, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - request_id_parameter=request_id_parameter, - lease_id=_lease_id, - owner=owner, - group=group, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_symbolic_link( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """get_symbolic_link. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["symboliclink"] = kwargs.pop("restype", _params.pop("restype", "symboliclink")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_get_symbolic_link_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-link-text"] = self._deserialize("str", response.headers.get("x-ms-link-text")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def create_hard_link( # pylint: disable=inconsistent-return-statements - self, - target_file: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Creates a hard link. - - :param target_file: NFS only. Required. Specifies the path of the target file to which the link - will be created, up to 2 KiB in length. It should be full path of the target from the root.The - target file must be in the same share and hence the same storage account. Required. - :type target_file: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["hardlink"] = kwargs.pop("restype", _params.pop("restype", "hardlink")) - file_type_constant: Literal["file"] = kwargs.pop("file_type_constant", _headers.pop("x-ms-type", "file")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_create_hard_link_request( - url=self._config.url, - target_file=target_file, - version=self._config.version, - timeout=timeout, - request_id_parameter=request_id_parameter, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - file_type_constant=file_type_constant, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-time") - ) - response_headers["x-ms-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") - ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") - ) - response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) - response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) - response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) - response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) - response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) - response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_operations.py new file mode 100644 index 000000000000..83f32b15d5d3 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_operations.py @@ -0,0 +1,8077 @@ +# pylint: disable=too-many-lines +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from collections.abc import MutableMapping +from io import IOBase +import json +from typing import Any, Callable, IO, Iterator, Literal, Optional, TypeVar, Union, overload + +from azure.core import PipelineClient +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, + map_error, +) +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._configuration import FileClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _deserialize_xml, _failsafe_deserialize_xml, _get_element +from .._utils.serialization import Deserializer, Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_directory_create_request( + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=directory" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if file_permission is not None: + _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") + if file_permission_key is not None: + _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") + if file_attributes is not None: + _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") + if file_creation_time is not None: + _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") + if file_last_write_time is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") + if file_change_time is not None: + _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") + if file_permission_format is not None: + _headers["x-ms-file-permission-format"] = _SERIALIZER.header( + "file_permission_format", file_permission_format, "str" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if owner is not None: + _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") + if group is not None: + _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") + if file_mode is not None: + _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") + if file_property_semantics is not None: + _headers["x-ms-file-property-semantics"] = _SERIALIZER.header( + "file_property_semantics", file_property_semantics, "str" + ) + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_directory_get_properties_request( + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=directory" + + # Construct parameters + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_directory_delete_request( + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=directory" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_directory_set_properties_request( + *, + timeout: Optional[int] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=directory&comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if file_permission is not None: + _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") + if file_permission_key is not None: + _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") + if file_attributes is not None: + _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") + if file_creation_time is not None: + _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") + if file_last_write_time is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") + if file_change_time is not None: + _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") + if file_permission_format is not None: + _headers["x-ms-file-permission-format"] = _SERIALIZER.header( + "file_permission_format", file_permission_format, "str" + ) + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if owner is not None: + _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") + if group is not None: + _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") + if file_mode is not None: + _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_directory_set_metadata_request( + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=directory&comp=metadata" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_directory_list_files_and_directories_segment_request( # pylint: disable=name-too-long + *, + prefix: Optional[str] = None, + sharesnapshot: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + include: Optional[list[Union[str, _models.ListFilesIncludeType]]] = None, + timeout: Optional[int] = None, + include_extended_info: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=directory&comp=list" + + # Construct parameters + if prefix is not None: + _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + if marker is not None: + _params["marker"] = _SERIALIZER.query("marker", marker, "str") + if maxresults is not None: + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") + if include is not None: + _params["include"] = _SERIALIZER.query("include", include, "[str]", div=",") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if include_extended_info is not None: + _headers["x-ms-file-extended-info"] = _SERIALIZER.header("include_extended_info", include_extended_info, "bool") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_directory_list_handles_request( + *, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?comp=listhandles" + + # Construct parameters + if marker is not None: + _params["marker"] = _SERIALIZER.query("marker", marker, "str") + if maxresults is not None: + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if recursive is not None: + _headers["x-ms-recursive"] = _SERIALIZER.header("recursive", recursive, "bool") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_directory_force_close_handles_request( # pylint: disable=name-too-long + *, + handle_id: str, + timeout: Optional[int] = None, + marker: Optional[str] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=forceclosehandles" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if marker is not None: + _params["marker"] = _SERIALIZER.query("marker", marker, "str") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-handle-id"] = _SERIALIZER.header("handle_id", handle_id, "str") + if recursive is not None: + _headers["x-ms-recursive"] = _SERIALIZER.header("recursive", recursive, "bool") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_directory_rename_request( + *, + rename_source: str, + timeout: Optional[int] = None, + replace_if_exists: Optional[bool] = None, + ignore_read_only: Optional[bool] = None, + source_lease_id: Optional[str] = None, + destination_lease_id: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=directory&comp=rename" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-file-rename-source"] = _SERIALIZER.header("rename_source", rename_source, "str") + if replace_if_exists is not None: + _headers["x-ms-file-rename-replace-if-exists"] = _SERIALIZER.header( + "replace_if_exists", replace_if_exists, "bool" + ) + if ignore_read_only is not None: + _headers["x-ms-file-rename-ignore-readonly"] = _SERIALIZER.header("ignore_read_only", ignore_read_only, "bool") + if source_lease_id is not None: + _headers["x-ms-source-lease-id"] = _SERIALIZER.header("source_lease_id", source_lease_id, "str") + if destination_lease_id is not None: + _headers["x-ms-destination-lease-id"] = _SERIALIZER.header("destination_lease_id", destination_lease_id, "str") + if file_attributes is not None: + _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") + if file_creation_time is not None: + _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") + if file_last_write_time is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") + if file_change_time is not None: + _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") + if file_permission is not None: + _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") + if file_permission_format is not None: + _headers["x-ms-file-permission-format"] = _SERIALIZER.header( + "file_permission_format", file_permission_format, "str" + ) + if file_permission_key is not None: + _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if allow_source_trailing_dot is not None: + _headers["x-ms-source-allow-trailing-dot"] = _SERIALIZER.header( + "allow_source_trailing_dot", allow_source_trailing_dot, "bool" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_create_request( # pylint: disable=too-many-locals,too-many-statements,too-many-branches + *, + file_content_length: int, + timeout: Optional[int] = None, + file_content_type: Optional[str] = None, + file_content_encoding: Optional[str] = None, + file_content_language: Optional[str] = None, + file_cache_control: Optional[str] = None, + file_content_md5: Optional[bytes] = None, + file_content_disposition: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, + content_md5: Optional[bytes] = None, + file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, + content_length: Optional[int] = None, + structured_body_type: Optional[str] = None, + structured_content_length: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + file_type: Literal["file"] = kwargs.pop("file_type", _headers.pop("x-ms-type", "file")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["x-ms-content-length"] = _SERIALIZER.header("file_content_length", file_content_length, "int") + _headers["x-ms-type"] = _SERIALIZER.header("file_type", file_type, "str") + if file_content_type is not None: + _headers["x-ms-content-type"] = _SERIALIZER.header("file_content_type", file_content_type, "str") + if file_content_encoding is not None: + _headers["x-ms-content-encoding"] = _SERIALIZER.header("file_content_encoding", file_content_encoding, "str") + if file_content_language is not None: + _headers["x-ms-content-language"] = _SERIALIZER.header("file_content_language", file_content_language, "str") + if file_cache_control is not None: + _headers["x-ms-cache-control"] = _SERIALIZER.header("file_cache_control", file_cache_control, "str") + if file_content_md5 is not None: + _headers["x-ms-content-md5"] = _SERIALIZER.header("file_content_md5", file_content_md5, "bytearray") + if file_content_disposition is not None: + _headers["x-ms-content-disposition"] = _SERIALIZER.header( + "file_content_disposition", file_content_disposition, "str" + ) + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if file_permission is not None: + _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") + if file_permission_key is not None: + _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") + if file_attributes is not None: + _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") + if file_creation_time is not None: + _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") + if file_last_write_time is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") + if file_change_time is not None: + _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") + if file_permission_format is not None: + _headers["x-ms-file-permission-format"] = _SERIALIZER.header( + "file_permission_format", file_permission_format, "str" + ) + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if owner is not None: + _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") + if group is not None: + _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") + if file_mode is not None: + _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") + if nfs_file_type is not None: + _headers["x-ms-file-file-type"] = _SERIALIZER.header("nfs_file_type", nfs_file_type, "str") + if content_md5 is not None: + _headers["Content-MD5"] = _SERIALIZER.header("content_md5", content_md5, "bytearray") + if file_property_semantics is not None: + _headers["x-ms-file-property-semantics"] = _SERIALIZER.header( + "file_property_semantics", file_property_semantics, "str" + ) + if content_length is not None: + _headers["Content-Length"] = _SERIALIZER.header("content_length", content_length, "int") + if structured_body_type is not None: + _headers["x-ms-structured-body"] = _SERIALIZER.header("structured_body_type", structured_body_type, "str") + if structured_content_length is not None: + _headers["x-ms-structured-content-length"] = _SERIALIZER.header( + "structured_content_length", structured_content_length, "int" + ) + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_download_request( + *, + timeout: Optional[int] = None, + range: Optional[str] = None, + range_get_content_md5: Optional[bool] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + structured_body_type: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/octet-stream") + + # Construct URL + _url = "" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if range is not None: + _headers["Range"] = _SERIALIZER.header("range", range, "str") + if range_get_content_md5 is not None: + _headers["x-ms-range-get-content-md5"] = _SERIALIZER.header( + "range_get_content_md5", range_get_content_md5, "bool" + ) + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if structured_body_type is not None: + _headers["x-ms-structured-body"] = _SERIALIZER.header("structured_body_type", structured_body_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_get_properties_request( + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "" + + # Construct parameters + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_delete_request( + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_set_http_headers_request( # pylint: disable=too-many-locals + *, + timeout: Optional[int] = None, + file_content_length: Optional[int] = None, + file_content_type: Optional[str] = None, + file_content_encoding: Optional[str] = None, + file_content_language: Optional[str] = None, + file_cache_control: Optional[str] = None, + file_content_md5: Optional[bytes] = None, + file_content_disposition: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if file_content_length is not None: + _headers["x-ms-content-length"] = _SERIALIZER.header("file_content_length", file_content_length, "int") + if file_content_type is not None: + _headers["x-ms-content-type"] = _SERIALIZER.header("file_content_type", file_content_type, "str") + if file_content_encoding is not None: + _headers["x-ms-content-encoding"] = _SERIALIZER.header("file_content_encoding", file_content_encoding, "str") + if file_content_language is not None: + _headers["x-ms-content-language"] = _SERIALIZER.header("file_content_language", file_content_language, "str") + if file_cache_control is not None: + _headers["x-ms-cache-control"] = _SERIALIZER.header("file_cache_control", file_cache_control, "str") + if file_content_md5 is not None: + _headers["x-ms-content-md5"] = _SERIALIZER.header("file_content_md5", file_content_md5, "bytearray") + if file_content_disposition is not None: + _headers["x-ms-content-disposition"] = _SERIALIZER.header( + "file_content_disposition", file_content_disposition, "str" + ) + if file_permission is not None: + _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") + if file_permission_key is not None: + _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") + if file_attributes is not None: + _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") + if file_creation_time is not None: + _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") + if file_last_write_time is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") + if file_change_time is not None: + _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") + if file_permission_format is not None: + _headers["x-ms-file-permission-format"] = _SERIALIZER.header( + "file_permission_format", file_permission_format, "str" + ) + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if owner is not None: + _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") + if group is not None: + _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") + if file_mode is not None: + _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_set_metadata_request( + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=metadata" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_acquire_lease_request( + *, + timeout: Optional[int] = None, + lease_duration: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if lease_duration is not None: + _headers["x-ms-lease-duration"] = _SERIALIZER.header("lease_duration", lease_duration, "int") + if proposed_lease_id is not None: + _headers["x-ms-proposed-lease-id"] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_release_lease_request( + *, + lease_id: str, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_change_lease_request( + *, + lease_id: str, + timeout: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if proposed_lease_id is not None: + _headers["x-ms-proposed-lease-id"] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_break_lease_request( + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_upload_range_request( + *, + range: str, + file_range_write: Union[str, _models.FileRangeWriteType], + content_length: int, + timeout: Optional[int] = None, + content_md5: Optional[bytes] = None, + lease_id: Optional[str] = None, + file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + structured_body_type: Optional[str] = None, + structured_content_length: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=range" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Range"] = _SERIALIZER.header("range", range, "str") + _headers["x-ms-write"] = _SERIALIZER.header("file_range_write", file_range_write, "str") + _headers["Content-Length"] = _SERIALIZER.header("content_length", content_length, "int") + if content_md5 is not None: + _headers["Content-MD5"] = _SERIALIZER.header("content_md5", content_md5, "bytearray") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if file_last_written_mode is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header( + "file_last_written_mode", file_last_written_mode, "str" + ) + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if structured_body_type is not None: + _headers["x-ms-structured-body"] = _SERIALIZER.header("structured_body_type", structured_body_type, "str") + if structured_content_length is not None: + _headers["x-ms-structured-content-length"] = _SERIALIZER.header( + "structured_content_length", structured_content_length, "int" + ) + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_upload_range_from_url_request( + *, + range: str, + copy_source: str, + file_range_write_from_url: Union[str, _models.FileRangeWriteFromUrlType], + content_length: int, + source_range: Optional[str] = None, + timeout: Optional[int] = None, + source_content_crc64: Optional[bytes] = None, + source_if_match_crc64: Optional[bytes] = None, + source_if_none_match_crc64: Optional[bytes] = None, + lease_id: Optional[str] = None, + copy_source_authorization: Optional[str] = None, + file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=range" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Range"] = _SERIALIZER.header("range", range, "str") + _headers["x-ms-copy-source"] = _SERIALIZER.header("copy_source", copy_source, "str") + if source_range is not None: + _headers["x-ms-source-range"] = _SERIALIZER.header("source_range", source_range, "str") + _headers["x-ms-write"] = _SERIALIZER.header("file_range_write_from_url", file_range_write_from_url, "str") + _headers["Content-Length"] = _SERIALIZER.header("content_length", content_length, "int") + if source_content_crc64 is not None: + _headers["x-ms-source-content-crc64"] = _SERIALIZER.header( + "source_content_crc64", source_content_crc64, "bytearray" + ) + if source_if_match_crc64 is not None: + _headers["x-ms-source-if-match-crc64"] = _SERIALIZER.header( + "source_if_match_crc64", source_if_match_crc64, "bytearray" + ) + if source_if_none_match_crc64 is not None: + _headers["x-ms-source-if-none-match-crc64"] = _SERIALIZER.header( + "source_if_none_match_crc64", source_if_none_match_crc64, "bytearray" + ) + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if copy_source_authorization is not None: + _headers["x-ms-copy-source-authorization"] = _SERIALIZER.header( + "copy_source_authorization", copy_source_authorization, "str" + ) + if file_last_written_mode is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header( + "file_last_written_mode", file_last_written_mode, "str" + ) + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if allow_source_trailing_dot is not None: + _headers["x-ms-source-allow-trailing-dot"] = _SERIALIZER.header( + "allow_source_trailing_dot", allow_source_trailing_dot, "bool" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_get_range_list_request( + *, + sharesnapshot: Optional[str] = None, + prevsharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + range: Optional[str] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + support_rename: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?comp=rangelist" + + # Construct parameters + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + if prevsharesnapshot is not None: + _params["prevsharesnapshot"] = _SERIALIZER.query("prevsharesnapshot", prevsharesnapshot, "str") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if range is not None: + _headers["Range"] = _SERIALIZER.header("range", range, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if support_rename is not None: + _headers["x-ms-file-support-rename"] = _SERIALIZER.header("support_rename", support_rename, "bool") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_start_copy_request( # pylint: disable=too-many-locals + *, + copy_source: str, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + file_permission_copy_mode: Optional[Union[str, _models.PermissionCopyModeType]] = None, + ignore_read_only: Optional[bool] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + set_archive_attribute: Optional[bool] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + file_mode_copy_mode: Optional[Union[str, _models.ModeCopyMode]] = None, + file_owner_copy_mode: Optional[Union[str, _models.OwnerCopyMode]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-copy-source"] = _SERIALIZER.header("copy_source", copy_source, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if file_permission is not None: + _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") + if file_permission_format is not None: + _headers["x-ms-file-permission-format"] = _SERIALIZER.header( + "file_permission_format", file_permission_format, "str" + ) + if file_permission_key is not None: + _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") + if file_permission_copy_mode is not None: + _headers["x-ms-file-permission-copy-mode"] = _SERIALIZER.header( + "file_permission_copy_mode", file_permission_copy_mode, "str" + ) + if ignore_read_only is not None: + _headers["x-ms-file-copy-ignore-readonly"] = _SERIALIZER.header("ignore_read_only", ignore_read_only, "bool") + if file_attributes is not None: + _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") + if file_creation_time is not None: + _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") + if file_last_write_time is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") + if file_change_time is not None: + _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") + if set_archive_attribute is not None: + _headers["x-ms-file-copy-set-archive"] = _SERIALIZER.header( + "set_archive_attribute", set_archive_attribute, "bool" + ) + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if allow_source_trailing_dot is not None: + _headers["x-ms-source-allow-trailing-dot"] = _SERIALIZER.header( + "allow_source_trailing_dot", allow_source_trailing_dot, "bool" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if owner is not None: + _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") + if group is not None: + _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") + if file_mode is not None: + _headers["x-ms-mode"] = _SERIALIZER.header("file_mode", file_mode, "str") + if file_mode_copy_mode is not None: + _headers["x-ms-file-mode-copy-mode"] = _SERIALIZER.header("file_mode_copy_mode", file_mode_copy_mode, "str") + if file_owner_copy_mode is not None: + _headers["x-ms-file-owner-copy-mode"] = _SERIALIZER.header("file_owner_copy_mode", file_owner_copy_mode, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_abort_copy_request( + *, + copyid: str, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + copy_action_abort_constant: Literal["abort"] = kwargs.pop( + "copy_action_abort_constant", _headers.pop("x-ms-copy-action", "abort") + ) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=copy" + + # Construct parameters + _params["copyid"] = _SERIALIZER.query("copyid", copyid, "str") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-copy-action"] = _SERIALIZER.header("copy_action_abort_constant", copy_action_abort_constant, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_list_handles_request( + *, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?comp=listhandles" + + # Construct parameters + if marker is not None: + _params["marker"] = _SERIALIZER.query("marker", marker, "str") + if maxresults is not None: + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_force_close_handles_request( + *, + handle_id: str, + timeout: Optional[int] = None, + marker: Optional[str] = None, + sharesnapshot: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=forceclosehandles" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if marker is not None: + _params["marker"] = _SERIALIZER.query("marker", marker, "str") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-handle-id"] = _SERIALIZER.header("handle_id", handle_id, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_rename_request( + *, + rename_source: str, + timeout: Optional[int] = None, + replace_if_exists: Optional[bool] = None, + ignore_read_only: Optional[bool] = None, + source_lease_id: Optional[str] = None, + destination_lease_id: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + file_content_type: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?comp=rename" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-file-rename-source"] = _SERIALIZER.header("rename_source", rename_source, "str") + if replace_if_exists is not None: + _headers["x-ms-file-rename-replace-if-exists"] = _SERIALIZER.header( + "replace_if_exists", replace_if_exists, "bool" + ) + if ignore_read_only is not None: + _headers["x-ms-file-rename-ignore-readonly"] = _SERIALIZER.header("ignore_read_only", ignore_read_only, "bool") + if source_lease_id is not None: + _headers["x-ms-source-lease-id"] = _SERIALIZER.header("source_lease_id", source_lease_id, "str") + if destination_lease_id is not None: + _headers["x-ms-destination-lease-id"] = _SERIALIZER.header("destination_lease_id", destination_lease_id, "str") + if file_attributes is not None: + _headers["x-ms-file-attributes"] = _SERIALIZER.header("file_attributes", file_attributes, "str") + if file_creation_time is not None: + _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") + if file_last_write_time is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") + if file_change_time is not None: + _headers["x-ms-file-change-time"] = _SERIALIZER.header("file_change_time", file_change_time, "str") + if file_permission is not None: + _headers["x-ms-file-permission"] = _SERIALIZER.header("file_permission", file_permission, "str") + if file_permission_format is not None: + _headers["x-ms-file-permission-format"] = _SERIALIZER.header( + "file_permission_format", file_permission_format, "str" + ) + if file_permission_key is not None: + _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if file_content_type is not None: + _headers["x-ms-content-type"] = _SERIALIZER.header("file_content_type", file_content_type, "str") + if allow_trailing_dot is not None: + _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if allow_source_trailing_dot is not None: + _headers["x-ms-source-allow-trailing-dot"] = _SERIALIZER.header( + "allow_source_trailing_dot", allow_source_trailing_dot, "bool" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_create_symbolic_link_request( + *, + link_text: str, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + lease_id: Optional[str] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=symboliclink" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if file_creation_time is not None: + _headers["x-ms-file-creation-time"] = _SERIALIZER.header("file_creation_time", file_creation_time, "str") + if file_last_write_time is not None: + _headers["x-ms-file-last-write-time"] = _SERIALIZER.header("file_last_write_time", file_last_write_time, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if owner is not None: + _headers["x-ms-owner"] = _SERIALIZER.header("owner", owner, "str") + if group is not None: + _headers["x-ms-group"] = _SERIALIZER.header("group", group, "str") + _headers["x-ms-link-text"] = _SERIALIZER.header("link_text", link_text, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_get_symbolic_link_request( + *, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=symboliclink" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_file_create_hard_link_request( + *, + target_file: str, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + file_type: Literal["file"] = kwargs.pop("file_type", _headers.pop("x-ms-type", "file")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=hardlink" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-type"] = _SERIALIZER.header("file_type", file_type, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + _headers["x-ms-file-target-file"] = _SERIALIZER.header("target_file", target_file, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_set_properties_request( + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "/?restype=service&comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_properties_request( + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/?restype=service&comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_list_shares_segment_request( # pylint: disable=name-too-long + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + include: Optional[list[Union[str, _models.ListSharesIncludeType]]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/?comp=list" + + # Construct parameters + if prefix is not None: + _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") + if marker is not None: + _params["marker"] = _SERIALIZER.query("marker", marker, "str") + if maxresults is not None: + _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if include is not None: + _params["include"] = _SERIALIZER.query("include", include, "[str]", div=",") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_service_get_user_delegation_key_request( # pylint: disable=name-too-long + *, timeout: Optional[int] = None, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "/?restype=service&comp=userdelegationkey" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_create_request( + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + quota: Optional[int] = None, + access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, + enabled_protocols: Optional[str] = None, + root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, + enable_snapshot_virtual_directory_access: Optional[bool] = None, + paid_bursting_enabled: Optional[bool] = None, + paid_bursting_max_iops: Optional[int] = None, + paid_bursting_max_bandwidth_mibps: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + share_provisioned_iops: Optional[int] = None, + share_provisioned_bandwidth_mibps: Optional[int] = None, + enable_smb_directory_lease: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if quota is not None: + _headers["x-ms-share-quota"] = _SERIALIZER.header("quota", quota, "int") + if access_tier is not None: + _headers["x-ms-access-tier"] = _SERIALIZER.header("access_tier", access_tier, "str") + if enabled_protocols is not None: + _headers["x-ms-enabled-protocols"] = _SERIALIZER.header("enabled_protocols", enabled_protocols, "str") + if root_squash is not None: + _headers["x-ms-root-squash"] = _SERIALIZER.header("root_squash", root_squash, "str") + if enable_snapshot_virtual_directory_access is not None: + _headers["x-ms-enable-snapshot-virtual-directory-access"] = _SERIALIZER.header( + "enable_snapshot_virtual_directory_access", enable_snapshot_virtual_directory_access, "bool" + ) + if paid_bursting_enabled is not None: + _headers["x-ms-share-paid-bursting-enabled"] = _SERIALIZER.header( + "paid_bursting_enabled", paid_bursting_enabled, "bool" + ) + if paid_bursting_max_iops is not None: + _headers["x-ms-share-paid-bursting-max-iops"] = _SERIALIZER.header( + "paid_bursting_max_iops", paid_bursting_max_iops, "int" + ) + if paid_bursting_max_bandwidth_mibps is not None: + _headers["x-ms-share-paid-bursting-max-bandwidth-mibps"] = _SERIALIZER.header( + "paid_bursting_max_bandwidth_mibps", paid_bursting_max_bandwidth_mibps, "int" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if share_provisioned_iops is not None: + _headers["x-ms-share-provisioned-iops"] = _SERIALIZER.header( + "share_provisioned_iops", share_provisioned_iops, "int" + ) + if share_provisioned_bandwidth_mibps is not None: + _headers["x-ms-share-provisioned-bandwidth-mibps"] = _SERIALIZER.header( + "share_provisioned_bandwidth_mibps", share_provisioned_bandwidth_mibps, "int" + ) + if enable_smb_directory_lease is not None: + _headers["x-ms-enable-smb-directory-lease"] = _SERIALIZER.header( + "enable_smb_directory_lease", enable_smb_directory_lease, "bool" + ) + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_get_properties_request( + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + lease_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share" + + # Construct parameters + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_delete_request( + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + lease_id: Optional[str] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share" + + # Construct parameters + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if delete_snapshots is not None: + _headers["x-ms-delete-snapshots"] = _SERIALIZER.header("delete_snapshots", delete_snapshots, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_acquire_lease_request( + *, + timeout: Optional[int] = None, + lease_duration: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if lease_duration is not None: + _headers["x-ms-lease-duration"] = _SERIALIZER.header("lease_duration", lease_duration, "int") + if proposed_lease_id is not None: + _headers["x-ms-proposed-lease-id"] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_release_lease_request( + *, + lease_id: str, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_change_lease_request( + *, + lease_id: str, + proposed_lease_id: Optional[str] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if proposed_lease_id is not None: + _headers["x-ms-proposed-lease-id"] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_renew_lease_request( + *, + lease_id: str, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["renew"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "renew")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_break_lease_request( + *, + timeout: Optional[int] = None, + break_period: Optional[int] = None, + lease_id: Optional[str] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=lease" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if break_period is not None: + _headers["x-ms-lease-break-period"] = _SERIALIZER.header("break_period", break_period, "int") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_create_snapshot_request( + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=snapshot" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_create_permission_request( + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=filepermission" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_get_permission_request( + *, + file_permission_key: str, + timeout: Optional[int] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "?restype=share&comp=filepermission" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") + if file_permission_format is not None: + _headers["x-ms-file-permission-format"] = _SERIALIZER.header( + "file_permission_format", file_permission_format, "str" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_set_properties_request( + *, + timeout: Optional[int] = None, + quota: Optional[int] = None, + access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, + lease_id: Optional[str] = None, + root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, + enable_snapshot_virtual_directory_access: Optional[bool] = None, + paid_bursting_enabled: Optional[bool] = None, + paid_bursting_max_iops: Optional[int] = None, + paid_bursting_max_bandwidth_mibps: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + share_provisioned_iops: Optional[int] = None, + share_provisioned_bandwidth_mibps: Optional[int] = None, + enable_smb_directory_lease: Optional[bool] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=properties" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if quota is not None: + _headers["x-ms-share-quota"] = _SERIALIZER.header("quota", quota, "int") + if access_tier is not None: + _headers["x-ms-access-tier"] = _SERIALIZER.header("access_tier", access_tier, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if root_squash is not None: + _headers["x-ms-root-squash"] = _SERIALIZER.header("root_squash", root_squash, "str") + if enable_snapshot_virtual_directory_access is not None: + _headers["x-ms-enable-snapshot-virtual-directory-access"] = _SERIALIZER.header( + "enable_snapshot_virtual_directory_access", enable_snapshot_virtual_directory_access, "bool" + ) + if paid_bursting_enabled is not None: + _headers["x-ms-share-paid-bursting-enabled"] = _SERIALIZER.header( + "paid_bursting_enabled", paid_bursting_enabled, "bool" + ) + if paid_bursting_max_iops is not None: + _headers["x-ms-share-paid-bursting-max-iops"] = _SERIALIZER.header( + "paid_bursting_max_iops", paid_bursting_max_iops, "int" + ) + if paid_bursting_max_bandwidth_mibps is not None: + _headers["x-ms-share-paid-bursting-max-bandwidth-mibps"] = _SERIALIZER.header( + "paid_bursting_max_bandwidth_mibps", paid_bursting_max_bandwidth_mibps, "int" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + if share_provisioned_iops is not None: + _headers["x-ms-share-provisioned-iops"] = _SERIALIZER.header( + "share_provisioned_iops", share_provisioned_iops, "int" + ) + if share_provisioned_bandwidth_mibps is not None: + _headers["x-ms-share-provisioned-bandwidth-mibps"] = _SERIALIZER.header( + "share_provisioned_bandwidth_mibps", share_provisioned_bandwidth_mibps, "int" + ) + if enable_smb_directory_lease is not None: + _headers["x-ms-enable-smb-directory-lease"] = _SERIALIZER.header( + "enable_smb_directory_lease", enable_smb_directory_lease, "bool" + ) + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_set_metadata_request( + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=metadata" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if metadata is not None: + _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_get_access_policy_request( + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=share&comp=acl" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_set_access_policy_request( + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=acl" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_get_statistics_request( + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + accept = _headers.pop("Accept", "application/xml") + + # Construct URL + _url = "?restype=share&comp=stats" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_share_restore_request( + *, + timeout: Optional[int] = None, + deleted_share_name: Optional[str] = None, + deleted_share_version: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) + # Construct URL + _url = "?restype=share&comp=undelete" + + # Construct parameters + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") + + # Construct headers + _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") + if deleted_share_name is not None: + _headers["x-ms-deleted-share-name"] = _SERIALIZER.header("deleted_share_name", deleted_share_name, "str") + if deleted_share_version is not None: + _headers["x-ms-deleted-share-version"] = _SERIALIZER.header( + "deleted_share_version", deleted_share_version, "str" + ) + if file_request_intent is not None: + _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +class DirectoryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.FileClient`'s + :attr:`directory` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FileClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def create( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Creates a new directory under the specified share or parent directory. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_permission: If specified the permission (security descriptor) shall be set for + the directory/file. This header can be used if Permission size is <= 8KB, else + x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as + input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or + x-ms-file-permission-key should be specified. Default value is None. + :paramtype file_permission: str + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default + value is None. + :paramtype file_permission_key: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value: 'Archive' for file and 'Directory' for directory. 'None' can also be specified as + default. Default value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file/directory. Default value: Now. + Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_change_time: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :keyword file_property_semantics: SMB only. Default value is New. Known values are: "New" and + "Restore". Default value is None. + :paramtype file_property_semantics: str or + ~azure.storage.fileshare.models.FilePropertySemantics + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_create_request( + timeout=timeout, + metadata=metadata, + file_permission=file_permission, + file_permission_key=file_permission_key, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission_format=file_permission_format, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + file_property_semantics=file_property_semantics, + allow_trailing_dot=allow_trailing_dot, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_properties( # pylint: disable=inconsistent-return-statements + self, + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Returns all system properties for the specified directory, and can also be used to check the + existence of a directory. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_get_properties_request( + sharesnapshot=sharesnapshot, + timeout=timeout, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-server-encrypted") + ) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Removes the specified empty directory. Note that the directory must be empty before it can be + deleted. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_delete_request( + timeout=timeout, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def set_properties( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + timeout: Optional[int] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + **kwargs: Any + ) -> None: + """Sets properties for the specified directory. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_permission: If specified the permission (security descriptor) shall be set for + the directory/file. This header can be used if Permission size is <= 8KB, else + x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as + input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or + x-ms-file-permission-key should be specified. Default value is None. + :paramtype file_permission: str + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default + value is None. + :paramtype file_permission_key: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value: 'Archive' for file and 'Directory' for directory. 'None' can also be specified as + default. Default value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file/directory. Default value: Now. + Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_change_time: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_set_properties_request( + timeout=timeout, + file_permission=file_permission, + file_permission_key=file_permission_key, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission_format=file_permission_format, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def set_metadata( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Sets one or more user-defined name-value pairs for the specified directory. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_set_metadata_request( + timeout=timeout, + metadata=metadata, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def list_files_and_directories_segment( + self, + *, + prefix: Optional[str] = None, + sharesnapshot: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + include: Optional[list[Union[str, _models.ListFilesIncludeType]]] = None, + timeout: Optional[int] = None, + include_extended_info: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.ListFilesAndDirectoriesSegmentResponse: + """Returns a list of files and directories under the specified share or directory. It lists the + contents only for a single level of the directory hierarchy. + + :keyword prefix: Filters the results to return only items whose name begins with the specified + prefix. Default value is None. + :paramtype prefix: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of items to return. Default value is None. + :paramtype maxresults: int + :keyword include: Include this parameter to specify one or more datasets to include in the + response. Default value is None. + :paramtype include: list[str or ~azure.storage.fileshare.models.ListFilesIncludeType] + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword include_extended_info: Include extended information. Default value is None. + :paramtype include_extended_info: bool + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: ListFilesAndDirectoriesSegmentResponse. The ListFilesAndDirectoriesSegmentResponse is + compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ListFilesAndDirectoriesSegmentResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListFilesAndDirectoriesSegmentResponse] = kwargs.pop("cls", None) + + _request = build_directory_list_files_and_directories_segment_request( + prefix=prefix, + sharesnapshot=sharesnapshot, + marker=marker, + maxresults=maxresults, + include=include, + timeout=timeout, + include_extended_info=include_extended_info, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListFilesAndDirectoriesSegmentResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_handles( + self, + *, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.ListHandlesResponse: + """Lists handles for directory. + + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of items to return. Default value is None. + :paramtype maxresults: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword recursive: Specifies operation should apply to the directory specified in the URI, its + files, its subdirectories and their files. Default value is None. + :paramtype recursive: bool + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) + + _request = build_directory_list_handles_request( + marker=marker, + maxresults=maxresults, + timeout=timeout, + sharesnapshot=sharesnapshot, + recursive=recursive, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListHandlesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def force_close_handles( # pylint: disable=inconsistent-return-statements + self, + *, + handle_id: str, + timeout: Optional[int] = None, + marker: Optional[str] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Closes all handles open for given directory. + + :keyword handle_id: Specifies handle ID opened on the file or directory to be closed. Asterisk + ('*') is a wildcard that specifies all handles. Required. + :paramtype handle_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword recursive: Specifies operation should apply to the directory specified in the URI, its + files, its subdirectories and their files. Default value is None. + :paramtype recursive: bool + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_force_close_handles_request( + handle_id=handle_id, + timeout=timeout, + marker=marker, + sharesnapshot=sharesnapshot, + recursive=recursive, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-marker"] = self._deserialize("str", response.headers.get("x-ms-marker")) + response_headers["x-ms-number-of-handles-closed"] = self._deserialize( + "int", response.headers.get("x-ms-number-of-handles-closed") + ) + response_headers["x-ms-number-of-handles-failed"] = self._deserialize( + "int", response.headers.get("x-ms-number-of-handles-failed") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def rename( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + rename_source: str, + timeout: Optional[int] = None, + replace_if_exists: Optional[bool] = None, + ignore_read_only: Optional[bool] = None, + source_lease_id: Optional[str] = None, + destination_lease_id: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Renames a directory. By default, the destination is overwritten and if the destination already + exists and has a read-only attribute set, the operation will fail. + + :keyword rename_source: Required. Specifies the URI-style path of the source file, up to 2 KB + in length. Required. + :paramtype rename_source: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword replace_if_exists: Boolean. Default value is false. Set to true to indicate that the + destination should be overwritten. Default value is None. + :paramtype replace_if_exists: bool + :keyword ignore_read_only: Boolean. Default value is false. Set to true to overwrite the + destination even if it has the read-only attribute set. Default value is None. + :paramtype ignore_read_only: bool + :keyword source_lease_id: Required if the source file has an active lease. Default value is + None. + :paramtype source_lease_id: str + :keyword destination_lease_id: Required if the destination has an active lease. Default value + is None. + :paramtype destination_lease_id: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the directory. Default value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the directory. Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the directory. Default value is None. + :paramtype file_change_time: str + :keyword file_permission: If specified the permission shall be set for the directory. Default + value is None. + :paramtype file_permission: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_permission_key: Key of the permission to be set. Default value is None. + :paramtype file_permission_key: str + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the + source URI. Default value is None. + :paramtype allow_source_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_directory_rename_request( + rename_source=rename_source, + timeout=timeout, + replace_if_exists=replace_if_exists, + ignore_read_only=ignore_read_only, + source_lease_id=source_lease_id, + destination_lease_id=destination_lease_id, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission=file_permission, + file_permission_format=file_permission_format, + file_permission_key=file_permission_key, + metadata=metadata, + allow_trailing_dot=allow_trailing_dot, + allow_source_trailing_dot=allow_source_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + +class FileOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.FileClient`'s + :attr:`file` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FileClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def create( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + optional_body: Optional[bytes] = None, + *, + file_content_length: int, + timeout: Optional[int] = None, + file_content_type: Optional[str] = None, + file_content_encoding: Optional[str] = None, + file_content_language: Optional[str] = None, + file_cache_control: Optional[str] = None, + file_content_md5: Optional[bytes] = None, + file_content_disposition: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, + content_md5: Optional[bytes] = None, + file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, + content_length: Optional[int] = None, + structured_body_type: Optional[str] = None, + structured_content_length: Optional[int] = None, + **kwargs: Any + ) -> None: + """Creates a new file or replaces a file. Note it only initializes the file with no content. + + :param optional_body: Initial data. Default value is None. + :type optional_body: bytes + :keyword file_content_length: Specifies the maximum size for the file, up to 4 TB. Required. + :paramtype file_content_length: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_content_type: Sets the MIME content type of the file. The default type is + 'application/octet-stream'. Default value is None. + :paramtype file_content_type: str + :keyword file_content_encoding: Specifies which content encodings have been applied to the + file. Default value is None. + :paramtype file_content_encoding: str + :keyword file_content_language: Specifies the natural languages used by this resource. Default + value is None. + :paramtype file_content_language: str + :keyword file_cache_control: Sets the file's cache control. The File service stores this value + but does not use or modify it. Default value is None. + :paramtype file_cache_control: str + :keyword file_content_md5: An MD5 hash of the file content. This hash is used to verify the + integrity of the file during transport. Default value is None. + :paramtype file_content_md5: bytes + :keyword file_content_disposition: Sets the file's Content-Disposition header. Default value is + None. + :paramtype file_content_disposition: str + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_permission: If specified the permission (security descriptor) shall be set for + the directory/file. This header can be used if Permission size is <= 8KB, else + x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as + input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or + x-ms-file-permission-key should be specified. Default value is None. + :paramtype file_permission: str + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default + value is None. + :paramtype file_permission_key: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value: 'Archive' for file and 'Directory' for directory. 'None' can also be specified as + default. Default value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file/directory. Default value: Now. + Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_change_time: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :keyword nfs_file_type: Optional, NFS only. Type of the file or directory. Known values are: + "Regular", "Directory", and "SymLink". Default value is None. + :paramtype nfs_file_type: str or ~azure.storage.fileshare.models.NfsFileType + :keyword content_md5: An MD5 hash of the content. This hash is used to verify the integrity of + the data during transport. Default value is None. + :paramtype content_md5: bytes + :keyword file_property_semantics: SMB only. Default value is New. Known values are: "New" and + "Restore". Default value is None. + :paramtype file_property_semantics: str or + ~azure.storage.fileshare.models.FilePropertySemantics + :keyword content_length: Specifies the number of bytes being transmitted in the request body. + When the x-ms-write header is set to clear, the value of this header must be set to zero.". + Default value is None. + :paramtype content_length: int + :keyword structured_body_type: Specifies the response content should be returned as a + structured message and specifies the message schema version and properties. Default value is + None. + :paramtype structured_body_type: str + :keyword structured_content_length: Required if the request body is a structured message. + Specifies the length of the blob/file content inside the message body. Will always be smaller + than Content-Length. Default value is None. + :paramtype structured_content_length: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + file_type: Literal["file"] = kwargs.pop("file_type", _headers.pop("x-ms-type", "file")) + content_type: Optional[str] = kwargs.pop( + "content_type", _headers.pop("Content-Type", "application/octet-stream") + ) + content_type = content_type if optional_body else None + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = optional_body + + _request = build_file_create_request( + file_content_length=file_content_length, + timeout=timeout, + file_content_type=file_content_type, + file_content_encoding=file_content_encoding, + file_content_language=file_content_language, + file_cache_control=file_cache_control, + file_content_md5=file_content_md5, + file_content_disposition=file_content_disposition, + metadata=metadata, + file_permission=file_permission, + file_permission_key=file_permission_key, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission_format=file_permission_format, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + nfs_file_type=nfs_file_type, + content_md5=content_md5, + file_property_semantics=file_property_semantics, + content_length=content_length, + structured_body_type=structured_body_type, + structured_content_length=structured_content_length, + file_type=file_type, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) + response_headers["x-ms-structured-body"] = self._deserialize( + "str", response.headers.get("x-ms-structured-body") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def download( + self, + *, + timeout: Optional[int] = None, + range: Optional[str] = None, + range_get_content_md5: Optional[bool] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + structured_body_type: Optional[str] = None, + **kwargs: Any + ) -> Iterator[bytes]: + """Reads or downloads a file from the system, including its metadata and properties. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword range: Return file data only from the specified byte range. Default value is None. + :paramtype range: str + :keyword range_get_content_md5: When this header is set to true and specified together with the + Range header, the service returns the MD5 hash for the range, as long as the range is less than + or equal to 4 MB in size. Default value is None. + :paramtype range_get_content_md5: bool + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword structured_body_type: Specifies the response content should be returned as a + structured message and specifies the message schema version and properties. Default value is + None. + :paramtype structured_body_type: str + :return: Iterator[bytes] + :rtype: Iterator[bytes] + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_file_download_request( + timeout=timeout, + range=range, + range_get_content_md5=range_get_content_md5, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + structured_body_type=structured_body_type, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", True) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 206]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) + response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) + response_headers["Content-Range"] = self._deserialize("str", response.headers.get("Content-Range")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["Content-Encoding"] = self._deserialize("str", response.headers.get("Content-Encoding")) + response_headers["Cache-Control"] = self._deserialize("str", response.headers.get("Cache-Control")) + response_headers["Content-Disposition"] = self._deserialize("str", response.headers.get("Content-Disposition")) + response_headers["Content-Language"] = self._deserialize("str", response.headers.get("Content-Language")) + response_headers["Accept-Ranges"] = self._deserialize("str", response.headers.get("Accept-Ranges")) + response_headers["x-ms-copy-completion-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-copy-completion-time") + ) + response_headers["x-ms-copy-status-description"] = self._deserialize( + "str", response.headers.get("x-ms-copy-status-description") + ) + response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) + response_headers["x-ms-copy-progress"] = self._deserialize("str", response.headers.get("x-ms-copy-progress")) + response_headers["x-ms-copy-source"] = self._deserialize("str", response.headers.get("x-ms-copy-source")) + response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) + response_headers["x-ms-content-md5"] = self._deserialize("bytearray", response.headers.get("x-ms-content-md5")) + response_headers["x-ms-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) + response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) + response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) + response_headers["x-ms-structured-body"] = self._deserialize( + "str", response.headers.get("x-ms-structured-body") + ) + response_headers["x-ms-structured-content-length"] = self._deserialize( + "int", response.headers.get("x-ms-structured-content-length") + ) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_properties( + self, + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> bool: + """Returns all user-defined metadata, standard HTTP properties, and system properties for the + file. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: bool + :rtype: bool + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_get_properties_request( + sharesnapshot=sharesnapshot, + timeout=timeout, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) + response_headers["x-ms-type"] = self._deserialize("str", response.headers.get("x-ms-type")) + response_headers["Content-Length"] = self._deserialize("int", response.headers.get("Content-Length")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["Content-Encoding"] = self._deserialize("str", response.headers.get("Content-Encoding")) + response_headers["Cache-Control"] = self._deserialize("str", response.headers.get("Cache-Control")) + response_headers["Content-Disposition"] = self._deserialize("str", response.headers.get("Content-Disposition")) + response_headers["Content-Language"] = self._deserialize("str", response.headers.get("Content-Language")) + response_headers["x-ms-copy-completion-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-copy-completion-time") + ) + response_headers["x-ms-copy-status-description"] = self._deserialize( + "str", response.headers.get("x-ms-copy-status-description") + ) + response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) + response_headers["x-ms-copy-progress"] = self._deserialize("str", response.headers.get("x-ms-copy-progress")) + response_headers["x-ms-copy-source"] = self._deserialize("str", response.headers.get("x-ms-copy-source")) + response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) + response_headers["x-ms-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) + response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) + response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Removes the file from the storage account. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_delete_request( + timeout=timeout, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + timeout: Optional[int] = None, + file_content_length: Optional[int] = None, + file_content_type: Optional[str] = None, + file_content_encoding: Optional[str] = None, + file_content_language: Optional[str] = None, + file_cache_control: Optional[str] = None, + file_content_md5: Optional[bytes] = None, + file_content_disposition: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_key: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + **kwargs: Any + ) -> None: + """Sets HTTP headers on a file. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_content_length: Specifies the number of bytes being transmitted. Default value is + None. + :paramtype file_content_length: int + :keyword file_content_type: Sets the MIME content type of the file. The default type is + 'application/octet-stream'. Default value is None. + :paramtype file_content_type: str + :keyword file_content_encoding: Specifies which content encodings have been applied to the + file. Default value is None. + :paramtype file_content_encoding: str + :keyword file_content_language: Specifies the natural languages used by this resource. Default + value is None. + :paramtype file_content_language: str + :keyword file_cache_control: Sets the file's cache control. The File service stores this value + but does not use or modify it. Default value is None. + :paramtype file_cache_control: str + :keyword file_content_md5: An MD5 hash of the file content. This hash is used to verify the + integrity of the file during transport. Default value is None. + :paramtype file_content_md5: bytes + :keyword file_content_disposition: Sets the file's Content-Disposition header. Default value is + None. + :paramtype file_content_disposition: str + :keyword file_permission: If specified the permission (security descriptor) shall be set for + the directory/file. This header can be used if Permission size is <= 8KB, else + x-ms-file-permission-key header shall be used. Default value: Inherit. If SDDL is specified as + input, it must have owner, group and dacl. Note: Only one of the x-ms-file-permission or + x-ms-file-permission-key should be specified. Default value is None. + :paramtype file_permission: str + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Default + value is None. + :paramtype file_permission_key: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value: 'Archive' for file and 'Directory' for directory. 'None' can also be specified as + default. Default value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file/directory. Default value: Now. + Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file/directory. Default value: Now. Default + value is None. + :paramtype file_change_time: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_set_http_headers_request( + timeout=timeout, + file_content_length=file_content_length, + file_content_type=file_content_type, + file_content_encoding=file_content_encoding, + file_content_language=file_content_language, + file_cache_control=file_cache_control, + file_content_md5=file_content_md5, + file_content_disposition=file_content_disposition, + file_permission=file_permission, + file_permission_key=file_permission_key, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission_format=file_permission_format, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def set_metadata( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Sets one or more user-defined name-value pairs for the specified file. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_set_metadata_request( + timeout=timeout, + metadata=metadata, + lease_id=lease_id, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def acquire_lease( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + lease_duration: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_duration: Specifies the duration of the lease, in seconds, or negative one (-1) + for a lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease + duration cannot be changed using renew or change. Default value is None. + :paramtype lease_duration: int + :keyword proposed_lease_id: Proposed lease ID, in a GUID string format. The File service + returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid + Constructor (String) for a list of valid GUID string formats. Default value is None. + :paramtype proposed_lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_acquire_lease_request( + timeout=timeout, + lease_duration=lease_duration, + proposed_lease_id=proposed_lease_id, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def release_lease( # pylint: disable=inconsistent-return-statements + self, + *, + lease_id: str, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_release_lease_request( + lease_id=lease_id, + timeout=timeout, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def change_lease( # pylint: disable=inconsistent-return-statements + self, + *, + lease_id: str, + timeout: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword proposed_lease_id: Proposed lease ID, in a GUID string format. The File service + returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid + Constructor (String) for a list of valid GUID string formats. Default value is None. + :paramtype proposed_lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_change_lease_request( + lease_id=lease_id, + timeout=timeout, + proposed_lease_id=proposed_lease_id, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def break_lease( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, + **kwargs: Any + ) -> None: + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_break_lease_request( + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + allow_trailing_dot=allow_trailing_dot, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-time"] = self._deserialize("int", response.headers.get("x-ms-lease-time")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def upload_range( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + optional_body: Optional[bytes] = None, + *, + range: str, + file_range_write: Union[str, _models.FileRangeWriteType], + content_length: int, + timeout: Optional[int] = None, + content_md5: Optional[bytes] = None, + lease_id: Optional[str] = None, + file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + structured_body_type: Optional[str] = None, + structured_content_length: Optional[int] = None, + **kwargs: Any + ) -> None: + """Upload a range of bytes to a file. + + :param optional_body: Initial data. Default value is None. + :type optional_body: bytes + :keyword range: Specifies the range of bytes to be written. Both the start and end of the range + must be specified. Required. + :paramtype range: str + :keyword file_range_write: Specify one of the following options: - Update: Writes the bytes + specified by the request body into the specified range. - Clear: Clears the specified range and + releases the space used in storage for that range. Known values are: "update" and "clear". + Required. + :paramtype file_range_write: str or ~azure.storage.fileshare.models.FileRangeWriteType + :keyword content_length: The number of bytes being transmitted in the request body. Required. + :paramtype content_length: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword content_md5: An MD5 hash of the content. This hash is used to verify the integrity of + the data during transport. Default value is None. + :paramtype content_md5: bytes + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_last_written_mode: If the file last write time should be preserved or + overwritten. Known values are: "Now" and "Preserve". Default value is None. + :paramtype file_last_written_mode: str or ~azure.storage.fileshare.models.FileLastWrittenMode + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword structured_body_type: Specifies the response content should be returned as a + structured message and specifies the message schema version and properties. Default value is + None. + :paramtype structured_body_type: str + :keyword structured_content_length: Required if the request body is a structured message. + Specifies the length of the blob/file content inside the message body. Will always be smaller + than Content-Length. Default value is None. + :paramtype structured_content_length: int + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop( + "content_type", _headers.pop("Content-Type", "application/octet-stream") + ) + content_type = content_type if optional_body else None + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = optional_body + + _request = build_file_upload_range_request( + range=range, + file_range_write=file_range_write, + content_length=content_length, + timeout=timeout, + content_md5=content_md5, + lease_id=lease_id, + file_last_written_mode=file_last_written_mode, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + structured_body_type=structured_body_type, + structured_content_length=structured_content_length, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-structured-body"] = self._deserialize( + "str", response.headers.get("x-ms-structured-body") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + range: str, + copy_source: str, + file_range_write_from_url: Union[str, _models.FileRangeWriteFromUrlType], + content_length: int, + source_range: Optional[str] = None, + timeout: Optional[int] = None, + source_content_crc64: Optional[bytes] = None, + source_if_match_crc64: Optional[bytes] = None, + source_if_none_match_crc64: Optional[bytes] = None, + lease_id: Optional[str] = None, + copy_source_authorization: Optional[str] = None, + file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Upload a range of bytes to a file where the contents are read from a URL. + + :keyword range: Specifies the range of bytes to be written. Both the start and end of the range + must be specified. Required. + :paramtype range: str + :keyword copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. + Required. + :paramtype copy_source: str + :keyword file_range_write_from_url: Only update is supported. "update" Required. + :paramtype file_range_write_from_url: str or + ~azure.storage.fileshare.models.FileRangeWriteFromUrlType + :keyword content_length: The number of bytes being transmitted in the request body. Required. + :paramtype content_length: int + :keyword source_range: Bytes of source data in the specified range. Default value is None. + :paramtype source_range: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword source_content_crc64: Specify the CRC64 hash of the source content. Default value is + None. + :paramtype source_content_crc64: bytes + :keyword source_if_match_crc64: Specify the CRC64 hash value to check for source content + integrity. Default value is None. + :paramtype source_if_match_crc64: bytes + :keyword source_if_none_match_crc64: Specify the CRC64 hash value to check for source content + mismatch. Default value is None. + :paramtype source_if_none_match_crc64: bytes + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword copy_source_authorization: Only Bearer type is supported. Credentials should be a + valid OAuth access token to copy source. Default value is None. + :paramtype copy_source_authorization: str + :keyword file_last_written_mode: If the file last write time should be preserved or + overwritten. Known values are: "Now" and "Preserve". Default value is None. + :paramtype file_last_written_mode: str or ~azure.storage.fileshare.models.FileLastWrittenMode + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the + source URI. Default value is None. + :paramtype allow_source_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_upload_range_from_url_request( + range=range, + copy_source=copy_source, + file_range_write_from_url=file_range_write_from_url, + content_length=content_length, + source_range=source_range, + timeout=timeout, + source_content_crc64=source_content_crc64, + source_if_match_crc64=source_if_match_crc64, + source_if_none_match_crc64=source_if_none_match_crc64, + lease_id=lease_id, + copy_source_authorization=copy_source_authorization, + file_last_written_mode=file_last_written_mode, + allow_trailing_dot=allow_trailing_dot, + allow_source_trailing_dot=allow_source_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["Content-MD5"] = self._deserialize("bytearray", response.headers.get("Content-MD5")) + response_headers["x-ms-content-crc64"] = self._deserialize( + "bytearray", response.headers.get("x-ms-content-crc64") + ) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_range_list( + self, + *, + sharesnapshot: Optional[str] = None, + prevsharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + range: Optional[str] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + support_rename: Optional[bool] = None, + **kwargs: Any + ) -> _models.ShareFileRangeList: + """Returns the list of valid page ranges for a file or snapshot of a file. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword prevsharesnapshot: The previous snapshot parameter is an opaque DateTime value that + specifies a previous file snapshot to compare against. Default value is None. + :paramtype prevsharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword range: Return file data only from the specified byte range. Default value is None. + :paramtype range: str + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword support_rename: This header is allowed only when PrevShareSnapshot query parameter is + set. Determines whether the changed ranges for a file that has been renamed or moved should be + listed. Default value is None. + :paramtype support_rename: bool + :return: ShareFileRangeList. The ShareFileRangeList is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ShareFileRangeList + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ShareFileRangeList] = kwargs.pop("cls", None) + + _request = build_file_get_range_list_request( + sharesnapshot=sharesnapshot, + prevsharesnapshot=prevsharesnapshot, + timeout=timeout, + range=range, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + support_rename=support_rename, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["x-ms-content-length"] = self._deserialize("int", response.headers.get("x-ms-content-length")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ShareFileRangeList, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def start_copy( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + copy_source: str, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + file_permission_copy_mode: Optional[Union[str, _models.PermissionCopyModeType]] = None, + ignore_read_only: Optional[bool] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + set_archive_attribute: Optional[bool] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_mode: Optional[str] = None, + file_mode_copy_mode: Optional[Union[str, _models.ModeCopyMode]] = None, + file_owner_copy_mode: Optional[Union[str, _models.OwnerCopyMode]] = None, + **kwargs: Any + ) -> None: + """Copies a blob or file to a destination file within the storage account. + + :keyword copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. + Required. + :paramtype copy_source: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_permission: If specified the permission shall be set for the file. Default value + is None. + :paramtype file_permission: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_permission_key: Key of the permission to be set. Default value is None. + :paramtype file_permission_key: str + :keyword file_permission_copy_mode: Specifies the option to copy file security descriptor from + source file or to set it using the value which is defined by the header value of + x-ms-file-permission or x-ms-file-permission-key. Known values are: "source" and "override". + Default value is None. + :paramtype file_permission_copy_mode: str or + ~azure.storage.fileshare.models.PermissionCopyModeType + :keyword ignore_read_only: A boolean value that specifies whether the ReadOnly attribute on a + preexisting destination file should be respected or overridden. Default value is None. + :paramtype ignore_read_only: bool + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file. Default value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file. Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file. Default value is None. + :paramtype file_change_time: str + :keyword set_archive_attribute: Optional. Sets the archive attribute on the destination file. + Default value is None. + :paramtype set_archive_attribute: bool + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the + source URI. Default value is None. + :paramtype allow_source_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_mode: Optional, NFS only. The file mode of the file or directory. Default value + is None. + :paramtype file_mode: str + :keyword file_mode_copy_mode: Specifies mode copy option for the file. Known values are: + "source" and "override". Default value is None. + :paramtype file_mode_copy_mode: str or ~azure.storage.fileshare.models.ModeCopyMode + :keyword file_owner_copy_mode: Specifies owner copy option for the file. Known values are: + "source" and "override". Default value is None. + :paramtype file_owner_copy_mode: str or ~azure.storage.fileshare.models.OwnerCopyMode + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_start_copy_request( + copy_source=copy_source, + timeout=timeout, + metadata=metadata, + file_permission=file_permission, + file_permission_format=file_permission_format, + file_permission_key=file_permission_key, + file_permission_copy_mode=file_permission_copy_mode, + ignore_read_only=ignore_read_only, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + set_archive_attribute=set_archive_attribute, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + allow_source_trailing_dot=allow_source_trailing_dot, + file_request_intent=file_request_intent, + owner=owner, + group=group, + file_mode=file_mode, + file_mode_copy_mode=file_mode_copy_mode, + file_owner_copy_mode=file_owner_copy_mode, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-copy-id"] = self._deserialize("str", response.headers.get("x-ms-copy-id")) + response_headers["x-ms-copy-status"] = self._deserialize("str", response.headers.get("x-ms-copy-status")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def abort_copy( # pylint: disable=inconsistent-return-statements + self, + *, + copyid: str, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Aborts a pending Copy File operation, and leaves a destination file with zero length and full + metadata. + + :keyword copyid: The copy identifier provided in the x-ms-copy-id header of the original Copy + File operation. Required. + :paramtype copyid: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + copy_action_abort_constant: Literal["abort"] = kwargs.pop( + "copy_action_abort_constant", _headers.pop("x-ms-copy-action", "abort") + ) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_abort_copy_request( + copyid=copyid, + timeout=timeout, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + copy_action_abort_constant=copy_action_abort_constant, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def list_handles( + self, + *, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.ListHandlesResponse: + """Lists handles for file. + + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of items to return. Default value is None. + :paramtype maxresults: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) + + _request = build_file_list_handles_request( + marker=marker, + maxresults=maxresults, + timeout=timeout, + sharesnapshot=sharesnapshot, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListHandlesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def force_close_handles( # pylint: disable=inconsistent-return-statements + self, + *, + handle_id: str, + timeout: Optional[int] = None, + marker: Optional[str] = None, + sharesnapshot: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Closes all handles open for given file. + + :keyword handle_id: Specifies handle ID opened on the file or directory to be closed. Asterisk + ('*') is a wildcard that specifies all handles. Required. + :paramtype handle_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_force_close_handles_request( + handle_id=handle_id, + timeout=timeout, + marker=marker, + sharesnapshot=sharesnapshot, + allow_trailing_dot=allow_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-marker"] = self._deserialize("str", response.headers.get("x-ms-marker")) + response_headers["x-ms-number-of-handles-closed"] = self._deserialize( + "int", response.headers.get("x-ms-number-of-handles-closed") + ) + response_headers["x-ms-number-of-handles-failed"] = self._deserialize( + "int", response.headers.get("x-ms-number-of-handles-failed") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def rename( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + rename_source: str, + timeout: Optional[int] = None, + replace_if_exists: Optional[bool] = None, + ignore_read_only: Optional[bool] = None, + source_lease_id: Optional[str] = None, + destination_lease_id: Optional[str] = None, + file_attributes: Optional[str] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + file_change_time: Optional[str] = None, + file_permission: Optional[str] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_permission_key: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + file_content_type: Optional[str] = None, + allow_trailing_dot: Optional[bool] = None, + allow_source_trailing_dot: Optional[bool] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Renames a file. By default, the destination is overwritten and if the destination already + exists and has a read-only attribute set, the operation will fail. + + :keyword rename_source: Required. Specifies the URI-style path of the source file, up to 2 KB + in length. Required. + :paramtype rename_source: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword replace_if_exists: Boolean. Default value is false. Set to true to indicate that the + destination should be overwritten. Default value is None. + :paramtype replace_if_exists: bool + :keyword ignore_read_only: Boolean. Default value is false. Set to true to overwrite the + destination even if it has the read-only attribute set. Default value is None. + :paramtype ignore_read_only: bool + :keyword source_lease_id: Required if the source file has an active lease. Default value is + None. + :paramtype source_lease_id: str + :keyword destination_lease_id: Required if the destination has an active lease. Default value + is None. + :paramtype destination_lease_id: str + :keyword file_attributes: If specified, the provided file attributes shall be set. Default + value is None. + :paramtype file_attributes: str + :keyword file_creation_time: Creation time for the file. Default value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file. Default value is None. + :paramtype file_last_write_time: str + :keyword file_change_time: Change time for the file. Default value is None. + :paramtype file_change_time: str + :keyword file_permission: If specified the permission shall be set for the file. Default value + is None. + :paramtype file_permission: str + :keyword file_permission_format: Optional. Used to set permission format. Known values are: + "Sddl" and "Binary". Default value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_permission_key: Key of the permission to be set. Default value is None. + :paramtype file_permission_key: str + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_content_type: Sets the MIME content type of the file. Default value is None. + :paramtype file_content_type: str + :keyword allow_trailing_dot: If true, the trailing dot will not be trimmed from the target + file/directory path. Default value is None. + :paramtype allow_trailing_dot: bool + :keyword allow_source_trailing_dot: If true, the trailing dot will not be trimmed from the + source URI. Default value is None. + :paramtype allow_source_trailing_dot: bool + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_rename_request( + rename_source=rename_source, + timeout=timeout, + replace_if_exists=replace_if_exists, + ignore_read_only=ignore_read_only, + source_lease_id=source_lease_id, + destination_lease_id=destination_lease_id, + file_attributes=file_attributes, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + file_change_time=file_change_time, + file_permission=file_permission, + file_permission_format=file_permission_format, + file_permission_key=file_permission_key, + metadata=metadata, + file_content_type=file_content_type, + allow_trailing_dot=allow_trailing_dot, + allow_source_trailing_dot=allow_source_trailing_dot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") + ) + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-file-attributes"] = self._deserialize( + "str", response.headers.get("x-ms-file-attributes") + ) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def create_symbolic_link( # pylint: disable=inconsistent-return-statements + self, + *, + link_text: str, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_creation_time: Optional[str] = None, + file_last_write_time: Optional[str] = None, + lease_id: Optional[str] = None, + owner: Optional[str] = None, + group: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Creates a symbolic link to a target file. NFS only. + + :keyword link_text: NFS only. The path to the original file, the symbolic link is pointing to. + Required. + :paramtype link_text: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_creation_time: Creation time for the file. Default value is None. + :paramtype file_creation_time: str + :keyword file_last_write_time: Last write time for the file. Default value is None. + :paramtype file_last_write_time: str + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword owner: Optional, NFS only. The owner of the file or directory. Default value is None. + :paramtype owner: str + :keyword group: Optional, NFS only. The owning group of the file or directory. Default value is + None. + :paramtype group: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_create_symbolic_link_request( + link_text=link_text, + timeout=timeout, + metadata=metadata, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + lease_id=lease_id, + owner=owner, + group=group, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_symbolic_link( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Returns the target of a symbolic link. NFS only. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_get_symbolic_link_request( + timeout=timeout, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-link-text"] = self._deserialize("str", response.headers.get("x-ms-link-text")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def create_hard_link( # pylint: disable=inconsistent-return-statements + self, + *, + target_file: str, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Creates a hard link to a target file. NFS only. + + :keyword target_file: NFS only. Required. Specifies the path of the target file to which the + link will be created, up to 2 KiB in length. Required. + :paramtype target_file: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + file_type: Literal["file"] = kwargs.pop("file_type", _headers.pop("x-ms-type", "file")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_file_create_hard_link_request( + target_file=target_file, + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + file_type=file_type, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-file-creation-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-creation-time") + ) + response_headers["x-ms-file-last-write-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-last-write-time") + ) + response_headers["x-ms-file-change-time"] = self._deserialize( + "str", response.headers.get("x-ms-file-change-time") + ) + response_headers["x-ms-file-id"] = self._deserialize("str", response.headers.get("x-ms-file-id")) + response_headers["x-ms-file-parent-id"] = self._deserialize("str", response.headers.get("x-ms-file-parent-id")) + response_headers["x-ms-link-count"] = self._deserialize("int", response.headers.get("x-ms-link-count")) + response_headers["x-ms-mode"] = self._deserialize("str", response.headers.get("x-ms-mode")) + response_headers["x-ms-owner"] = self._deserialize("str", response.headers.get("x-ms-owner")) + response_headers["x-ms-group"] = self._deserialize("str", response.headers.get("x-ms-group")) + response_headers["x-ms-file-file-type"] = self._deserialize("str", response.headers.get("x-ms-file-file-type")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.FileClient`'s + :attr:`service` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FileClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def set_properties( # pylint: disable=inconsistent-return-statements + self, + storage_service_properties: _models.StorageServiceProperties, + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Sets properties for a storage account's File service endpoint, including properties for Storage + Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. + + :param storage_service_properties: Storage service properties. Required. + :type storage_service_properties: + ~azure.storage.fileshare._generated.models.StorageServiceProperties + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _content = _get_element(storage_service_properties) + + _request = build_service_set_properties_request( + timeout=timeout, + file_request_intent=file_request_intent, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_properties( + self, + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.StorageServiceProperties: + """Gets the properties of a storage account's File service, including properties for Storage + Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: StorageServiceProperties. The StorageServiceProperties is compatible with + MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.StorageServiceProperties + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.StorageServiceProperties] = kwargs.pop("cls", None) + + _request = build_service_get_properties_request( + timeout=timeout, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.StorageServiceProperties, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_shares_segment( + self, + *, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + include: Optional[list[Union[str, _models.ListSharesIncludeType]]] = None, + **kwargs: Any + ) -> _models.ListSharesResponse: + """The List Shares Segment operation returns a list of the shares and share snapshots under the + specified account. + + :keyword prefix: Filters the results to return only items whose name begins with the specified + prefix. Default value is None. + :paramtype prefix: str + :keyword marker: A string value that identifies the portion of the list to be returned with the + next listing operation. Default value is None. + :paramtype marker: str + :keyword maxresults: Specifies the maximum number of items to return. Default value is None. + :paramtype maxresults: int + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword include: Include this parameter to specify one or more datasets to include in the + response. Default value is None. + :paramtype include: list[str or ~azure.storage.fileshare.models.ListSharesIncludeType] + :return: ListSharesResponse. The ListSharesResponse is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ListSharesResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ListSharesResponse] = kwargs.pop("cls", None) + + _request = build_service_list_shares_segment_request( + prefix=prefix, + marker=marker, + maxresults=maxresults, + timeout=timeout, + file_request_intent=file_request_intent, + include=include, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ListSharesResponse, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_user_delegation_key( + self, key_info: _models.KeyInfo, *, timeout: Optional[int] = None, **kwargs: Any + ) -> _models.UserDelegationKey: + """Retrieves a user delegation key for the File service. This can be used to generate a user + delegation SAS. + + :param key_info: Key information. Required. + :type key_info: ~azure.storage.fileshare._generated.models.KeyInfo + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :return: UserDelegationKey. The UserDelegationKey is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.UserDelegationKey + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) + + _content = _get_element(key_info) + + _request = build_service_get_user_delegation_key_request( + timeout=timeout, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.UserDelegationKey, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + +class ShareOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.FileClient`'s + :attr:`share` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: FileClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def create( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + quota: Optional[int] = None, + access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, + enabled_protocols: Optional[str] = None, + root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, + enable_snapshot_virtual_directory_access: Optional[bool] = None, + paid_bursting_enabled: Optional[bool] = None, + paid_bursting_max_iops: Optional[int] = None, + paid_bursting_max_bandwidth_mibps: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + share_provisioned_iops: Optional[int] = None, + share_provisioned_bandwidth_mibps: Optional[int] = None, + enable_smb_directory_lease: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Creates a new share under the specified account. If the share with the same name already + exists, the operation fails. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword quota: Specifies the maximum size of the share, in gigabytes. Default value is None. + :paramtype quota: int + :keyword access_tier: Specifies the access tier of the share. Known values are: + "TransactionOptimized", "Hot", "Cool", and "Premium". Default value is None. + :paramtype access_tier: str or ~azure.storage.fileshare.models.ShareAccessTier + :keyword enabled_protocols: Protocols to enable on the share. Default value is None. + :paramtype enabled_protocols: str + :keyword root_squash: Root squash to set on the share. Only valid for NFS shares. Known values + are: "NoRootSquash", "RootSquash", and "AllSquash". Default value is None. + :paramtype root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash + :keyword enable_snapshot_virtual_directory_access: Optional. Used to enable snapshot virtual + directory access. Default value is None. + :paramtype enable_snapshot_virtual_directory_access: bool + :keyword paid_bursting_enabled: Optional. Boolean. Default if not specified is false. This + property enables paid bursting. Default value is None. + :paramtype paid_bursting_enabled: bool + :keyword paid_bursting_max_iops: Optional. Integer. Default if not specified is the maximum + IOPS the file share can support. Current maximum for a file share is 102,400 IOPS. Default + value is None. + :paramtype paid_bursting_max_iops: int + :keyword paid_bursting_max_bandwidth_mibps: Optional. Integer. Default if not specified is the + maximum throughput the file share can support. Current maximum for a file share is 10,340 + MiB/sec. Default value is None. + :paramtype paid_bursting_max_bandwidth_mibps: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword share_provisioned_iops: Optional. Specifies the provisioned IOPS of the share. Default + value is None. + :paramtype share_provisioned_iops: int + :keyword share_provisioned_bandwidth_mibps: Optional. Specifies the provisioned bandwidth of + the share, in MiBps. Default value is None. + :paramtype share_provisioned_bandwidth_mibps: int + :keyword enable_smb_directory_lease: Optional. Used to enable SMB directory lease. Default + value is None. + :paramtype enable_smb_directory_lease: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_create_request( + timeout=timeout, + metadata=metadata, + quota=quota, + access_tier=access_tier, + enabled_protocols=enabled_protocols, + root_squash=root_squash, + enable_snapshot_virtual_directory_access=enable_snapshot_virtual_directory_access, + paid_bursting_enabled=paid_bursting_enabled, + paid_bursting_max_iops=paid_bursting_max_iops, + paid_bursting_max_bandwidth_mibps=paid_bursting_max_bandwidth_mibps, + file_request_intent=file_request_intent, + share_provisioned_iops=share_provisioned_iops, + share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, + enable_smb_directory_lease=enable_smb_directory_lease, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) + response_headers["x-ms-share-provisioned-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-iops") + ) + response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") + ) + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") + ) + response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_properties( # pylint: disable=inconsistent-return-statements + self, + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + lease_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """Returns all user-defined metadata and system properties for the specified share or share + snapshot. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_get_properties_request( + sharesnapshot=sharesnapshot, + timeout=timeout, + file_request_intent=file_request_intent, + lease_id=lease_id, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) + response_headers["x-ms-share-provisioned-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-iops") + ) + response_headers["x-ms-share-provisioned-ingress-mbps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-ingress-mbps") + ) + response_headers["x-ms-share-provisioned-egress-mbps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-egress-mbps") + ) + response_headers["x-ms-share-next-allowed-quota-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-quota-downgrade-time") + ) + response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") + ) + response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) + response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) + response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) + response_headers["x-ms-access-tier"] = self._deserialize("str", response.headers.get("x-ms-access-tier")) + response_headers["x-ms-access-tier-change-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-access-tier-change-time") + ) + response_headers["x-ms-access-tier-transition-state"] = self._deserialize( + "str", response.headers.get("x-ms-access-tier-transition-state") + ) + response_headers["x-ms-enabled-protocols"] = self._deserialize( + "str", response.headers.get("x-ms-enabled-protocols") + ) + response_headers["x-ms-root-squash"] = self._deserialize("str", response.headers.get("x-ms-root-squash")) + response_headers["x-ms-enable-snapshot-virtual-directory-access"] = self._deserialize( + "bool", response.headers.get("x-ms-enable-snapshot-virtual-directory-access") + ) + response_headers["x-ms-share-paid-bursting-enabled"] = self._deserialize( + "bool", response.headers.get("x-ms-share-paid-bursting-enabled") + ) + response_headers["x-ms-share-paid-bursting-max-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-paid-bursting-max-iops") + ) + response_headers["x-ms-share-paid-bursting-max-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-paid-bursting-max-bandwidth-mibps") + ) + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") + ) + response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + ) + response_headers["x-ms-share-next-allowed-provisioned-iops-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-iops-downgrade-time") + ) + response_headers["x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time") + ) + response_headers["x-ms-enable-smb-directory-lease"] = self._deserialize( + "bool", response.headers.get("x-ms-enable-smb-directory-lease") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def delete( # pylint: disable=inconsistent-return-statements + self, + *, + sharesnapshot: Optional[str] = None, + timeout: Optional[int] = None, + delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + lease_id: Optional[str] = None, + **kwargs: Any + ) -> None: + """Operation marks the specified share or share snapshot for deletion. The share or share snapshot + and any files contained within it are later deleted during garbage collection. + + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword delete_snapshots: Specifies the option include to delete the base share and all of its + snapshots. Known values are: "include" and "include-leased". Default value is None. + :paramtype delete_snapshots: str or ~azure.storage.fileshare.models.DeleteSnapshotsOptionType + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_delete_request( + sharesnapshot=sharesnapshot, + timeout=timeout, + delete_snapshots=delete_snapshots, + file_request_intent=file_request_intent, + lease_id=lease_id, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-file-share-usage-bytes"] = self._deserialize( + "int", response.headers.get("x-ms-file-share-usage-bytes") + ) + response_headers["x-ms-file-share-snapshot-usage-bytes"] = self._deserialize( + "int", response.headers.get("x-ms-file-share-snapshot-usage-bytes") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def acquire_lease( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + lease_duration: Optional[int] = None, + proposed_lease_id: Optional[str] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_duration: Specifies the duration of the lease, in seconds, or negative one (-1) + for a lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease + duration cannot be changed using renew or change. Default value is None. + :paramtype lease_duration: int + :keyword proposed_lease_id: Proposed lease ID, in a GUID string format. The File service + returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid + Constructor (String) for a list of valid GUID string formats. Default value is None. + :paramtype proposed_lease_id: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_acquire_lease_request( + timeout=timeout, + lease_duration=lease_duration, + proposed_lease_id=proposed_lease_id, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def release_lease( # pylint: disable=inconsistent-return-statements + self, + *, + lease_id: str, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_release_lease_request( + lease_id=lease_id, + timeout=timeout, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def change_lease( # pylint: disable=inconsistent-return-statements + self, + *, + lease_id: str, + proposed_lease_id: Optional[str] = None, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword proposed_lease_id: Proposed lease ID, in a GUID string format. The File service + returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid + Constructor (String) for a list of valid GUID string formats. Default value is None. + :paramtype proposed_lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_change_lease_request( + lease_id=lease_id, + proposed_lease_id=proposed_lease_id, + timeout=timeout, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def renew_lease( # pylint: disable=inconsistent-return-statements + self, + *, + lease_id: str, + timeout: Optional[int] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword lease_id: Specifies the current lease ID on the resource. Required. + :paramtype lease_id: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["renew"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "renew")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_renew_lease_request( + lease_id=lease_id, + timeout=timeout, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def break_lease( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + break_period: Optional[int] = None, + lease_id: Optional[str] = None, + sharesnapshot: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """The Lease Share operation establishes and manages a lock on a share for delete operations. The + lock duration can be 15 to 60 seconds, or can be infinite. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword break_period: For a break operation, proposed duration the lease should continue + before it is broken, in seconds, between 0 and 60. This break period is only used if it is + shorter than the time remaining on the lease. If longer, the time remaining on the lease is + used. A new lease will not be available before the break period has expired, but the lease may + be held for longer than the break period. If this header does not appear with a break + operation, a fixed-duration lease breaks after the remaining lease period elapses, and an + infinite lease breaks immediately. Default value is None. + :paramtype break_period: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a + share snapshot. Default value is None. + :paramtype sharesnapshot: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_break_lease_request( + timeout=timeout, + break_period=break_period, + lease_id=lease_id, + sharesnapshot=sharesnapshot, + file_request_intent=file_request_intent, + action=action, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-lease-time"] = self._deserialize("int", response.headers.get("x-ms-lease-time")) + response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def create_snapshot( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Creates a read-only snapshot of a share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_create_snapshot_request( + timeout=timeout, + metadata=metadata, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-snapshot"] = self._deserialize("str", response.headers.get("x-ms-snapshot")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @overload + def create_permission( + self, + permission: _models.SharePermission, + *, + content_type: str = "application/json", + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. + + :param permission: A permission (a security descriptor) at the share level. Required. + :type permission: ~azure.storage.fileshare._generated.models.SharePermission + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_permission( + self, + permission: JSON, + *, + content_type: str = "application/json", + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. + + :param permission: A permission (a security descriptor) at the share level. Required. + :type permission: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_permission( + self, + permission: IO[bytes], + *, + content_type: str = "application/json", + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. + + :param permission: A permission (a security descriptor) at the share level. Required. + :type permission: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_permission( # pylint: disable=inconsistent-return-statements + self, + permission: Union[_models.SharePermission, JSON, IO[bytes]], + *, + timeout: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. + + :param permission: A permission (a security descriptor) at the share level. Is one of the + following types: SharePermission, JSON, IO[bytes] Required. + :type permission: ~azure.storage.fileshare._generated.models.SharePermission or JSON or + IO[bytes] + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(permission, (IOBase, bytes)): + _content = permission + else: + _content = json.dumps(permission, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_share_create_permission_request( + timeout=timeout, + file_request_intent=file_request_intent, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-file-permission-key"] = self._deserialize( + "str", response.headers.get("x-ms-file-permission-key") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_permission( + self, + *, + file_permission_key: str, + timeout: Optional[int] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.SharePermission: + """Returns the permission (security descriptor) for a given permission key. This is used to + support file level ACLs for SMB shares. + + :keyword file_permission_key: Key of the permission to be set for the directory/file. Note: + Only one of the x-ms-file-permission or x-ms-file-permission-key should be specified. Required. + :paramtype file_permission_key: str + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword file_permission_format: Optional. Specifies the format in which the permission is + returned. Acceptable values are SDDL or binary. Known values are: "Sddl" and "Binary". Default + value is None. + :paramtype file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: SharePermission. The SharePermission is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.SharePermission + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SharePermission] = kwargs.pop("cls", None) + + _request = build_share_get_permission_request( + file_permission_key=file_permission_key, + timeout=timeout, + file_permission_format=file_permission_format, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SharePermission, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def set_properties( # pylint: disable=inconsistent-return-statements,too-many-locals + self, + *, + timeout: Optional[int] = None, + quota: Optional[int] = None, + access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, + lease_id: Optional[str] = None, + root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, + enable_snapshot_virtual_directory_access: Optional[bool] = None, + paid_bursting_enabled: Optional[bool] = None, + paid_bursting_max_iops: Optional[int] = None, + paid_bursting_max_bandwidth_mibps: Optional[int] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + share_provisioned_iops: Optional[int] = None, + share_provisioned_bandwidth_mibps: Optional[int] = None, + enable_smb_directory_lease: Optional[bool] = None, + **kwargs: Any + ) -> None: + """Sets properties for the specified share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword quota: Specifies the maximum size of the share, in gigabytes. Default value is None. + :paramtype quota: int + :keyword access_tier: Specifies the access tier of the share. Known values are: + "TransactionOptimized", "Hot", "Cool", and "Premium". Default value is None. + :paramtype access_tier: str or ~azure.storage.fileshare.models.ShareAccessTier + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword root_squash: Root squash to set on the share. Only valid for NFS shares. Known values + are: "NoRootSquash", "RootSquash", and "AllSquash". Default value is None. + :paramtype root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash + :keyword enable_snapshot_virtual_directory_access: Optional. Used to enable snapshot virtual + directory access. Default value is None. + :paramtype enable_snapshot_virtual_directory_access: bool + :keyword paid_bursting_enabled: Optional. Boolean. Default if not specified is false. This + property enables paid bursting. Default value is None. + :paramtype paid_bursting_enabled: bool + :keyword paid_bursting_max_iops: Optional. Integer. Default if not specified is the maximum + IOPS the file share can support. Current maximum for a file share is 102,400 IOPS. Default + value is None. + :paramtype paid_bursting_max_iops: int + :keyword paid_bursting_max_bandwidth_mibps: Optional. Integer. Default if not specified is the + maximum throughput the file share can support. Current maximum for a file share is 10,340 + MiB/sec. Default value is None. + :paramtype paid_bursting_max_bandwidth_mibps: int + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :keyword share_provisioned_iops: Optional. Specifies the provisioned IOPS of the share. Default + value is None. + :paramtype share_provisioned_iops: int + :keyword share_provisioned_bandwidth_mibps: Optional. Specifies the provisioned bandwidth of + the share, in MiBps. Default value is None. + :paramtype share_provisioned_bandwidth_mibps: int + :keyword enable_smb_directory_lease: Optional. Used to enable SMB directory lease. Default + value is None. + :paramtype enable_smb_directory_lease: bool + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_set_properties_request( + timeout=timeout, + quota=quota, + access_tier=access_tier, + lease_id=lease_id, + root_squash=root_squash, + enable_snapshot_virtual_directory_access=enable_snapshot_virtual_directory_access, + paid_bursting_enabled=paid_bursting_enabled, + paid_bursting_max_iops=paid_bursting_max_iops, + paid_bursting_max_bandwidth_mibps=paid_bursting_max_bandwidth_mibps, + file_request_intent=file_request_intent, + share_provisioned_iops=share_provisioned_iops, + share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, + enable_smb_directory_lease=enable_smb_directory_lease, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) + response_headers["x-ms-share-provisioned-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-iops") + ) + response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") + ) + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") + ) + response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + ) + response_headers["x-ms-share-next-allowed-quota-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-quota-downgrade-time") + ) + response_headers["x-ms-share-next-allowed-provisioned-iops-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-iops-downgrade-time") + ) + response_headers["x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time"] = self._deserialize( + "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def set_metadata( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Sets one or more user-defined name-value pairs for the specified share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword metadata: Optional. User-defined metadata for the resource. Default value is None. + :paramtype metadata: dict[str, str] + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_set_metadata_request( + timeout=timeout, + metadata=metadata, + lease_id=lease_id, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_access_policy( + self, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.SignedIdentifiers: + """Returns information about stored access policies specified on the share that may be used with + Shared Access Signatures. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.SignedIdentifiers + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) + + _request = build_share_get_access_policy_request( + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.SignedIdentifiers, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def set_access_policy( # pylint: disable=inconsistent-return-statements + self, + share_acl: Optional[_models.SignedIdentifiers] = None, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Sets stored access policies for the share that may be used with Shared Access Signatures. + + :param share_acl: The ACL for the share. Default value is None. + :type share_acl: ~azure.storage.fileshare._generated.models.SignedIdentifiers + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + content_type = content_type if share_acl else None + cls: ClsType[None] = kwargs.pop("cls", None) + + if share_acl is not None: + _content = _get_element(share_acl) + else: + _content = None + + _request = build_share_set_access_policy_request( + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + content_type=content_type, + version=self._config.version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore + + @distributed_trace + def get_statistics( + self, + *, + timeout: Optional[int] = None, + lease_id: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> _models.ShareStats: + """Retrieves statistics related to the share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + value is None. + :paramtype lease_id: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: ShareStats. The ShareStats is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.ShareStats + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.ShareStats] = kwargs.pop("cls", None) + + _request = build_share_get_statistics_request( + timeout=timeout, + lease_id=lease_id, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize_xml(_models.ShareStats, response.text()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def restore( # pylint: disable=inconsistent-return-statements + self, + *, + timeout: Optional[int] = None, + deleted_share_name: Optional[str] = None, + deleted_share_version: Optional[str] = None, + file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + **kwargs: Any + ) -> None: + """Restores a previously deleted share. + + :keyword timeout: The timeout parameter is expressed in seconds. Default value is None. + :paramtype timeout: int + :keyword deleted_share_name: Specifies the name of the previously-deleted share. Default value + is None. + :paramtype deleted_share_name: str + :keyword deleted_share_version: Specifies the version of the previously-deleted share. Default + value is None. + :paramtype deleted_share_version: str + :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_share_restore_request( + timeout=timeout, + deleted_share_name=deleted_share_name, + deleted_share_version=deleted_share_version, + file_request_intent=file_request_intent, + version=self._config.version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "url": self._serialize.url("self._config.url", self._config.url, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize_xml( + _models.Error, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) + response_headers["x-ms-share-provisioned-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-iops") + ) + response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( + "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") + ) + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") + ) + response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + ) + response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) + response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) + + if cls: + return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_patch.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_patch.py index f7dd32510333..ea765788358a 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_patch.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_patch.py @@ -1,14 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_service_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_service_operations.py deleted file mode 100644 index 11db434df4f1..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_service_operations.py +++ /dev/null @@ -1,543 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from typing import Any, Callable, Literal, Optional, TypeVar, Union - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import AzureFileStorageConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_set_properties_request( - url: str, - *, - content: Any, - version: str, - timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_get_properties_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_shares_segment_request( - url: str, - *, - version: str, - prefix: Optional[str] = None, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - include: Optional[list[Union[str, _models.ListSharesIncludeType]]] = None, - timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["list"] = kwargs.pop("comp", _params.pop("comp", "list")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if prefix is not None: - _params["prefix"] = _SERIALIZER.query("prefix", prefix, "str") - if marker is not None: - _params["marker"] = _SERIALIZER.query("marker", marker, "str") - if maxresults is not None: - _params["maxresults"] = _SERIALIZER.query("maxresults", maxresults, "int", minimum=1) - if include is not None: - _params["include"] = _SERIALIZER.query("include", include, "[str]", div=",") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_user_delegation_key_request( - url: str, - *, - content: Any, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["userdelegationkey"] = kwargs.pop("comp", _params.pop("comp", "userdelegationkey")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -class ServiceOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare.AzureFileStorage`'s - :attr:`service` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureFileStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def set_properties( # pylint: disable=inconsistent-return-statements - self, storage_service_properties: _models.StorageServiceProperties, timeout: Optional[int] = None, **kwargs: Any - ) -> None: - """Sets properties for a storage account's File service endpoint, including properties for Storage - Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. - - :param storage_service_properties: The StorageService properties. Required. - :type storage_service_properties: ~azure.storage.fileshare.models.StorageServiceProperties - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _content = self._serialize.body(storage_service_properties, "StorageServiceProperties", is_xml=True) - - _request = build_set_properties_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_properties(self, timeout: Optional[int] = None, **kwargs: Any) -> _models.StorageServiceProperties: - """Gets the properties of a storage account's File service, including properties for Storage - Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: StorageServiceProperties or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.StorageServiceProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - cls: ClsType[_models.StorageServiceProperties] = kwargs.pop("cls", None) - - _request = build_get_properties_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - - deserialized = self._deserialize("StorageServiceProperties", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_shares_segment( - self, - prefix: Optional[str] = None, - marker: Optional[str] = None, - maxresults: Optional[int] = None, - include: Optional[list[Union[str, _models.ListSharesIncludeType]]] = None, - timeout: Optional[int] = None, - **kwargs: Any - ) -> _models.ListSharesResponse: - """The List Shares Segment operation returns a list of the shares and share snapshots under the - specified account. - - :param prefix: Filters the results to return only entries whose name begins with the specified - prefix. Default value is None. - :type prefix: str - :param marker: A string value that identifies the portion of the list to be returned with the - next list operation. The operation returns a marker value within the response body if the list - returned was not complete. The marker value may then be used in a subsequent call to request - the next set of list items. The marker value is opaque to the client. Default value is None. - :type marker: str - :param maxresults: Specifies the maximum number of entries to return. If the request does not - specify maxresults, or specifies a value greater than 5,000, the server will return up to 5,000 - items. Default value is None. - :type maxresults: int - :param include: Include this parameter to specify one or more datasets to include in the - response. Default value is None. - :type include: list[str or ~azure.storage.fileshare.models.ListSharesIncludeType] - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: ListSharesResponse or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ListSharesResponse - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["list"] = kwargs.pop("comp", _params.pop("comp", "list")) - cls: ClsType[_models.ListSharesResponse] = kwargs.pop("cls", None) - - _request = build_list_shares_segment_request( - url=self._config.url, - version=self._config.version, - prefix=prefix, - marker=marker, - maxresults=maxresults, - include=include, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - - deserialized = self._deserialize("ListSharesResponse", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_user_delegation_key( - self, - key_info: _models.KeyInfo, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> _models.UserDelegationKey: - """Retrieves a user delegation key for the File service. This is only a valid operation when using - bearer token authentication. - - :param key_info: Key information. Required. - :type key_info: ~azure.storage.fileshare.models.KeyInfo - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: UserDelegationKey or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.UserDelegationKey - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["service"] = kwargs.pop("restype", _params.pop("restype", "service")) - comp: Literal["userdelegationkey"] = kwargs.pop("comp", _params.pop("comp", "userdelegationkey")) - content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) - cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) - - _content = self._serialize.body(key_info, "KeyInfo", is_xml=True) - - _request = build_get_user_delegation_key_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - request_id_parameter=request_id_parameter, - restype=restype, - comp=comp, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("UserDelegationKey", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_share_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_share_operations.py deleted file mode 100644 index 464f7e4f6614..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_share_operations.py +++ /dev/null @@ -1,2651 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from collections.abc import MutableMapping -from io import IOBase -from typing import Any, Callable, IO, Literal, Optional, TypeVar, Union, overload - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import AzureFileStorageConfiguration -from .._utils.serialization import Deserializer, Serializer - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - quota: Optional[int] = None, - access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, - enabled_protocols: Optional[str] = None, - root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, - enable_snapshot_virtual_directory_access: Optional[bool] = None, - paid_bursting_enabled: Optional[bool] = None, - paid_bursting_max_bandwidth_mibps: Optional[int] = None, - paid_bursting_max_iops: Optional[int] = None, - share_provisioned_iops: Optional[int] = None, - share_provisioned_bandwidth_mibps: Optional[int] = None, - enable_smb_directory_lease: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - if quota is not None: - _headers["x-ms-share-quota"] = _SERIALIZER.header("quota", quota, "int", minimum=1) - if access_tier is not None: - _headers["x-ms-access-tier"] = _SERIALIZER.header("access_tier", access_tier, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if enabled_protocols is not None: - _headers["x-ms-enabled-protocols"] = _SERIALIZER.header("enabled_protocols", enabled_protocols, "str") - if root_squash is not None: - _headers["x-ms-root-squash"] = _SERIALIZER.header("root_squash", root_squash, "str") - if enable_snapshot_virtual_directory_access is not None: - _headers["x-ms-enable-snapshot-virtual-directory-access"] = _SERIALIZER.header( - "enable_snapshot_virtual_directory_access", enable_snapshot_virtual_directory_access, "bool" - ) - if paid_bursting_enabled is not None: - _headers["x-ms-share-paid-bursting-enabled"] = _SERIALIZER.header( - "paid_bursting_enabled", paid_bursting_enabled, "bool" - ) - if paid_bursting_max_bandwidth_mibps is not None: - _headers["x-ms-share-paid-bursting-max-bandwidth-mibps"] = _SERIALIZER.header( - "paid_bursting_max_bandwidth_mibps", paid_bursting_max_bandwidth_mibps, "int" - ) - if paid_bursting_max_iops is not None: - _headers["x-ms-share-paid-bursting-max-iops"] = _SERIALIZER.header( - "paid_bursting_max_iops", paid_bursting_max_iops, "int" - ) - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if share_provisioned_iops is not None: - _headers["x-ms-share-provisioned-iops"] = _SERIALIZER.header( - "share_provisioned_iops", share_provisioned_iops, "int" - ) - if share_provisioned_bandwidth_mibps is not None: - _headers["x-ms-share-provisioned-bandwidth-mibps"] = _SERIALIZER.header( - "share_provisioned_bandwidth_mibps", share_provisioned_bandwidth_mibps, "int" - ) - if enable_smb_directory_lease is not None: - _headers["x-ms-enable-smb-directory-lease"] = _SERIALIZER.header( - "enable_smb_directory_lease", enable_smb_directory_lease, "bool" - ) - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_properties_request( - url: str, - *, - version: str, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - lease_id: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - url: str, - *, - version: str, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, - lease_id: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if delete_snapshots is not None: - _headers["x-ms-delete-snapshots"] = _SERIALIZER.header("delete_snapshots", delete_snapshots, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_acquire_lease_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - duration: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - if duration is not None: - _headers["x-ms-lease-duration"] = _SERIALIZER.header("duration", duration, "int") - if proposed_lease_id is not None: - _headers["x-ms-proposed-lease-id"] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_release_lease_request( - url: str, - *, - lease_id: str, - version: str, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_change_lease_request( - url: str, - *, - lease_id: str, - version: str, - timeout: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if proposed_lease_id is not None: - _headers["x-ms-proposed-lease-id"] = _SERIALIZER.header("proposed_lease_id", proposed_lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_renew_lease_request( - url: str, - *, - lease_id: str, - version: str, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["renew"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "renew")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_break_lease_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - break_period: Optional[int] = None, - lease_id: Optional[str] = None, - request_id_parameter: Optional[str] = None, - sharesnapshot: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - if sharesnapshot is not None: - _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") - - # Construct headers - _headers["x-ms-lease-action"] = _SERIALIZER.header("action", action, "str") - if break_period is not None: - _headers["x-ms-lease-break-period"] = _SERIALIZER.header("break_period", break_period, "int") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_snapshot_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["snapshot"] = kwargs.pop("comp", _params.pop("comp", "snapshot")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_create_permission_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["filepermission"] = kwargs.pop("comp", _params.pop("comp", "filepermission")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_permission_request( - url: str, - *, - file_permission_key: str, - version: str, - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["filepermission"] = kwargs.pop("comp", _params.pop("comp", "filepermission")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-file-permission-key"] = _SERIALIZER.header("file_permission_key", file_permission_key, "str") - if file_permission_format is not None: - _headers["x-ms-file-permission-format"] = _SERIALIZER.header( - "file_permission_format", file_permission_format, "str" - ) - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_properties_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - quota: Optional[int] = None, - access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, - lease_id: Optional[str] = None, - root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, - enable_snapshot_virtual_directory_access: Optional[bool] = None, - paid_bursting_enabled: Optional[bool] = None, - paid_bursting_max_bandwidth_mibps: Optional[int] = None, - paid_bursting_max_iops: Optional[int] = None, - share_provisioned_iops: Optional[int] = None, - share_provisioned_bandwidth_mibps: Optional[int] = None, - enable_smb_directory_lease: Optional[bool] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if quota is not None: - _headers["x-ms-share-quota"] = _SERIALIZER.header("quota", quota, "int", minimum=1) - if access_tier is not None: - _headers["x-ms-access-tier"] = _SERIALIZER.header("access_tier", access_tier, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if root_squash is not None: - _headers["x-ms-root-squash"] = _SERIALIZER.header("root_squash", root_squash, "str") - if enable_snapshot_virtual_directory_access is not None: - _headers["x-ms-enable-snapshot-virtual-directory-access"] = _SERIALIZER.header( - "enable_snapshot_virtual_directory_access", enable_snapshot_virtual_directory_access, "bool" - ) - if paid_bursting_enabled is not None: - _headers["x-ms-share-paid-bursting-enabled"] = _SERIALIZER.header( - "paid_bursting_enabled", paid_bursting_enabled, "bool" - ) - if paid_bursting_max_bandwidth_mibps is not None: - _headers["x-ms-share-paid-bursting-max-bandwidth-mibps"] = _SERIALIZER.header( - "paid_bursting_max_bandwidth_mibps", paid_bursting_max_bandwidth_mibps, "int" - ) - if paid_bursting_max_iops is not None: - _headers["x-ms-share-paid-bursting-max-iops"] = _SERIALIZER.header( - "paid_bursting_max_iops", paid_bursting_max_iops, "int" - ) - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if share_provisioned_iops is not None: - _headers["x-ms-share-provisioned-iops"] = _SERIALIZER.header( - "share_provisioned_iops", share_provisioned_iops, "int" - ) - if share_provisioned_bandwidth_mibps is not None: - _headers["x-ms-share-provisioned-bandwidth-mibps"] = _SERIALIZER.header( - "share_provisioned_bandwidth_mibps", share_provisioned_bandwidth_mibps, "int" - ) - if enable_smb_directory_lease is not None: - _headers["x-ms-enable-smb-directory-lease"] = _SERIALIZER.header( - "enable_smb_directory_lease", enable_smb_directory_lease, "bool" - ) - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_metadata_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - lease_id: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{str}") - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_access_policy_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - lease_id: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_set_access_policy_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - lease_id: Optional[str] = None, - content: Any = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_get_statistics_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - lease_id: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["stats"] = kwargs.pop("comp", _params.pop("comp", "stats")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_restore_request( - url: str, - *, - version: str, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - deleted_share_name: Optional[str] = None, - deleted_share_version: Optional[str] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["undelete"] = kwargs.pop("comp", _params.pop("comp", "undelete")) - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = kwargs.pop("template_url", "{url}") - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str", skip_quote=True), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - if timeout is not None: - _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int", minimum=0) - - # Construct headers - _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - if request_id_parameter is not None: - _headers["x-ms-client-request-id"] = _SERIALIZER.header("request_id_parameter", request_id_parameter, "str") - if deleted_share_name is not None: - _headers["x-ms-deleted-share-name"] = _SERIALIZER.header("deleted_share_name", deleted_share_name, "str") - if deleted_share_version is not None: - _headers["x-ms-deleted-share-version"] = _SERIALIZER.header( - "deleted_share_version", deleted_share_version, "str" - ) - if file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -class ShareOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare.AzureFileStorage`'s - :attr:`share` attribute. - """ - - models = _models - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: AzureFileStorageConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def create( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - quota: Optional[int] = None, - access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, - enabled_protocols: Optional[str] = None, - root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, - enable_snapshot_virtual_directory_access: Optional[bool] = None, - paid_bursting_enabled: Optional[bool] = None, - paid_bursting_max_bandwidth_mibps: Optional[int] = None, - paid_bursting_max_iops: Optional[int] = None, - share_provisioned_iops: Optional[int] = None, - share_provisioned_bandwidth_mibps: Optional[int] = None, - enable_smb_directory_lease: Optional[bool] = None, - **kwargs: Any - ) -> None: - """Creates a new share under the specified account. If the share with the same name already - exists, the operation fails. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param quota: Specifies the maximum size of the share, in gigabytes. Default value is None. - :type quota: int - :param access_tier: Specifies the access tier of the share. Known values are: - "TransactionOptimized", "Hot", "Cool", and "Premium". Default value is None. - :type access_tier: str or ~azure.storage.fileshare.models.ShareAccessTier - :param enabled_protocols: Protocols to enable on the share. Default value is None. - :type enabled_protocols: str - :param root_squash: Root squash to set on the share. Only valid for NFS shares. Known values - are: "NoRootSquash", "RootSquash", and "AllSquash". Default value is None. - :type root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash - :param enable_snapshot_virtual_directory_access: Default value is None. - :type enable_snapshot_virtual_directory_access: bool - :param paid_bursting_enabled: Optional. Boolean. Default if not specified is false. This - property enables paid bursting. Default value is None. - :type paid_bursting_enabled: bool - :param paid_bursting_max_bandwidth_mibps: Optional. Integer. Default if not specified is the - maximum throughput the file share can support. Current maximum for a file share is 10,340 - MiB/sec. Default value is None. - :type paid_bursting_max_bandwidth_mibps: int - :param paid_bursting_max_iops: Optional. Integer. Default if not specified is the maximum IOPS - the file share can support. Current maximum for a file share is 102,400 IOPS. Default value is - None. - :type paid_bursting_max_iops: int - :param share_provisioned_iops: Optional. Supported in version 2025-01-05 and later. Only - allowed for provisioned v2 file shares. Specifies the provisioned number of input/output - operations per second (IOPS) of the share. If this is not specified, the provisioned IOPS is - set to value calculated based on recommendation formula. Default value is None. - :type share_provisioned_iops: int - :param share_provisioned_bandwidth_mibps: Optional. Supported in version 2025-01-05 and later. - Only allowed for provisioned v2 file shares. Specifies the provisioned bandwidth of the share, - in mebibytes per second (MiBps). If this is not specified, the provisioned bandwidth is set to - value calculated based on recommendation formula. Default value is None. - :type share_provisioned_bandwidth_mibps: int - :param enable_smb_directory_lease: SMB only, default is true. Specifies whether granting of - new directory leases for directories present in a share are to be enabled or disabled. An input - of true specifies that granting of new directory leases is to be allowed. An input of false - specifies that granting of new directory leases is to be blocked. Default value is None. - :type enable_smb_directory_lease: bool - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_create_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - quota=quota, - access_tier=access_tier, - enabled_protocols=enabled_protocols, - root_squash=root_squash, - enable_snapshot_virtual_directory_access=enable_snapshot_virtual_directory_access, - paid_bursting_enabled=paid_bursting_enabled, - paid_bursting_max_bandwidth_mibps=paid_bursting_max_bandwidth_mibps, - paid_bursting_max_iops=paid_bursting_max_iops, - share_provisioned_iops=share_provisioned_iops, - share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, - enable_smb_directory_lease=enable_smb_directory_lease, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) - response_headers["x-ms-share-provisioned-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-iops") - ) - response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") - ) - response_headers["x-ms-share-included-burst-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-included-burst-iops") - ) - response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_properties( # pylint: disable=inconsistent-return-statements - self, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Returns all user-defined metadata and system properties for the specified share or share - snapshot. The data returned does not include the share's list of files. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_properties_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - timeout=timeout, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-meta"] = self._deserialize("{str}", response.headers.get("x-ms-meta")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) - response_headers["x-ms-share-provisioned-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-iops") - ) - response_headers["x-ms-share-provisioned-ingress-mbps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-ingress-mbps") - ) - response_headers["x-ms-share-provisioned-egress-mbps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-egress-mbps") - ) - response_headers["x-ms-share-next-allowed-quota-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-quota-downgrade-time") - ) - response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") - ) - response_headers["x-ms-lease-duration"] = self._deserialize("str", response.headers.get("x-ms-lease-duration")) - response_headers["x-ms-lease-state"] = self._deserialize("str", response.headers.get("x-ms-lease-state")) - response_headers["x-ms-lease-status"] = self._deserialize("str", response.headers.get("x-ms-lease-status")) - response_headers["x-ms-access-tier"] = self._deserialize("str", response.headers.get("x-ms-access-tier")) - response_headers["x-ms-access-tier-change-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-access-tier-change-time") - ) - response_headers["x-ms-access-tier-transition-state"] = self._deserialize( - "str", response.headers.get("x-ms-access-tier-transition-state") - ) - response_headers["x-ms-enabled-protocols"] = self._deserialize( - "str", response.headers.get("x-ms-enabled-protocols") - ) - response_headers["x-ms-root-squash"] = self._deserialize("str", response.headers.get("x-ms-root-squash")) - response_headers["x-ms-enable-snapshot-virtual-directory-access"] = self._deserialize( - "bool", response.headers.get("x-ms-enable-snapshot-virtual-directory-access") - ) - response_headers["x-ms-share-paid-bursting-enabled"] = self._deserialize( - "bool", response.headers.get("x-ms-share-paid-bursting-enabled") - ) - response_headers["x-ms-share-paid-bursting-max-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-paid-bursting-max-iops") - ) - response_headers["x-ms-share-paid-bursting-max-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-paid-bursting-max-bandwidth-mibps") - ) - response_headers["x-ms-share-included-burst-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-included-burst-iops") - ) - response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") - ) - response_headers["x-ms-share-next-allowed-provisioned-iops-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-iops-downgrade-time") - ) - response_headers["x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time") - ) - response_headers["x-ms-enable-smb-directory-lease"] = self._deserialize( - "bool", response.headers.get("x-ms-enable-smb-directory-lease") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements - self, - sharesnapshot: Optional[str] = None, - timeout: Optional[int] = None, - delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Operation marks the specified share or share snapshot for deletion. The share or share snapshot - and any files contained within it are later deleted during garbage collection. - - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param delete_snapshots: Specifies the option include to delete the base share and all of its - snapshots. Known values are: "include" and "include-leased". Default value is None. - :type delete_snapshots: str or ~azure.storage.fileshare.models.DeleteSnapshotsOptionType - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_delete_request( - url=self._config.url, - version=self._config.version, - sharesnapshot=sharesnapshot, - timeout=timeout, - delete_snapshots=delete_snapshots, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-file-share-usage-bytes"] = self._deserialize( - "int", response.headers.get("x-ms-file-share-usage-bytes") - ) - response_headers["x-ms-file-share-snapshot-usage-bytes"] = self._deserialize( - "int", response.headers.get("x-ms-file-share-snapshot-usage-bytes") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def acquire_lease( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - duration: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param duration: Specifies the duration of the lease, in seconds, or negative one (-1) for a - lease that never expires. A non-infinite lease can be between 15 and 60 seconds. A lease - duration cannot be changed using renew or change. Default value is None. - :type duration: int - :param proposed_lease_id: Proposed lease ID, in a GUID string format. The File service returns - 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid - Constructor (String) for a list of valid GUID string formats. Default value is None. - :type proposed_lease_id: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_acquire_lease_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - duration=duration, - proposed_lease_id=proposed_lease_id, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def release_lease( # pylint: disable=inconsistent-return-statements - self, - lease_id: str, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_release_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def change_lease( # pylint: disable=inconsistent-return-statements - self, - lease_id: str, - timeout: Optional[int] = None, - proposed_lease_id: Optional[str] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param proposed_lease_id: Proposed lease ID, in a GUID string format. The File service returns - 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid - Constructor (String) for a list of valid GUID string formats. Default value is None. - :type proposed_lease_id: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_change_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - proposed_lease_id=proposed_lease_id, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def renew_lease( # pylint: disable=inconsistent-return-statements - self, - lease_id: str, - timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - request_id_parameter: Optional[str] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param lease_id: Specifies the current lease ID on the resource. Required. - :type lease_id: str - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["renew"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "renew")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_renew_lease_request( - url=self._config.url, - lease_id=lease_id, - version=self._config.version, - timeout=timeout, - sharesnapshot=sharesnapshot, - request_id_parameter=request_id_parameter, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def break_lease( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - break_period: Optional[int] = None, - request_id_parameter: Optional[str] = None, - sharesnapshot: Optional[str] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """The Lease Share operation establishes and manages a lock on a share, or the specified snapshot - for set and delete share operations. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param break_period: For a break operation, proposed duration the lease should continue before - it is broken, in seconds, between 0 and 60. This break period is only used if it is shorter - than the time remaining on the lease. If longer, the time remaining on the lease is used. A new - lease will not be available before the break period has expired, but the lease may be held for - longer than the break period. If this header does not appear with a break operation, a - fixed-duration lease breaks after the remaining lease period elapses, and an infinite lease - breaks immediately. Default value is None. - :type break_period: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param sharesnapshot: The snapshot parameter is an opaque DateTime value that, when present, - specifies the share snapshot to query. Default value is None. - :type sharesnapshot: str - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp: Literal["lease"] = kwargs.pop("comp", _params.pop("comp", "lease")) - action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_break_lease_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - break_period=break_period, - lease_id=_lease_id, - request_id_parameter=request_id_parameter, - sharesnapshot=sharesnapshot, - file_request_intent=self._config.file_request_intent, - comp=comp, - action=action, - restype=restype, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-lease-time"] = self._deserialize("int", response.headers.get("x-ms-lease-time")) - response_headers["x-ms-lease-id"] = self._deserialize("str", response.headers.get("x-ms-lease-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def create_snapshot( # pylint: disable=inconsistent-return-statements - self, timeout: Optional[int] = None, metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> None: - """Creates a read-only snapshot of a share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["snapshot"] = kwargs.pop("comp", _params.pop("comp", "snapshot")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_create_snapshot_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-snapshot"] = self._deserialize("str", response.headers.get("x-ms-snapshot")) - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @overload - def create_permission( - self, - share_permission: _models.SharePermission, - timeout: Optional[int] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Create a permission (a security descriptor). - - :param share_permission: A permission (a security descriptor) at the share level. Required. - :type share_permission: ~azure.storage.fileshare.models.SharePermission - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_permission( - self, - share_permission: IO[bytes], - timeout: Optional[int] = None, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> None: - """Create a permission (a security descriptor). - - :param share_permission: A permission (a security descriptor) at the share level. Required. - :type share_permission: IO[bytes] - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_permission( # pylint: disable=inconsistent-return-statements - self, share_permission: Union[_models.SharePermission, IO[bytes]], timeout: Optional[int] = None, **kwargs: Any - ) -> None: - """Create a permission (a security descriptor). - - :param share_permission: A permission (a security descriptor) at the share level. Is either a - SharePermission type or a IO[bytes] type. Required. - :type share_permission: ~azure.storage.fileshare.models.SharePermission or IO[bytes] - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["filepermission"] = kwargs.pop("comp", _params.pop("comp", "filepermission")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[None] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _json = None - _content = None - if isinstance(share_permission, (IOBase, bytes)): - _content = share_permission - else: - _json = self._serialize.body(share_permission, "SharePermission") - - _request = build_create_permission_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - content_type=content_type, - json=_json, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-file-permission-key"] = self._deserialize( - "str", response.headers.get("x-ms-file-permission-key") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_permission( - self, - file_permission_key: str, - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = None, - timeout: Optional[int] = None, - **kwargs: Any - ) -> _models.SharePermission: - """Returns the permission (security descriptor) for a given key. - - :param file_permission_key: Key of the permission to be set for the directory/file. Required. - :type file_permission_key: str - :param file_permission_format: Optional. Available for version 2023-06-01 and later. Specifies - the format in which the permission is returned. Acceptable values are SDDL or binary. If - x-ms-file-permission-format is unspecified or explicitly set to SDDL, the permission is - returned in SDDL format. If x-ms-file-permission-format is explicitly set to binary, the - permission is returned as a base64 string representing the binary encoding of the permission. - Known values are: "Sddl" and "Binary". Default value is None. - :type file_permission_format: str or ~azure.storage.fileshare.models.FilePermissionFormat - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :return: SharePermission or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.SharePermission - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["filepermission"] = kwargs.pop("comp", _params.pop("comp", "filepermission")) - cls: ClsType[_models.SharePermission] = kwargs.pop("cls", None) - - _request = build_get_permission_request( - url=self._config.url, - file_permission_key=file_permission_key, - version=self._config.version, - file_permission_format=file_permission_format, - timeout=timeout, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("SharePermission", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def set_properties( # pylint: disable=inconsistent-return-statements,too-many-locals - self, - timeout: Optional[int] = None, - quota: Optional[int] = None, - access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, - root_squash: Optional[Union[str, _models.ShareRootSquash]] = None, - enable_snapshot_virtual_directory_access: Optional[bool] = None, - paid_bursting_enabled: Optional[bool] = None, - paid_bursting_max_bandwidth_mibps: Optional[int] = None, - paid_bursting_max_iops: Optional[int] = None, - share_provisioned_iops: Optional[int] = None, - share_provisioned_bandwidth_mibps: Optional[int] = None, - enable_smb_directory_lease: Optional[bool] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Sets properties for the specified share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param quota: Specifies the maximum size of the share, in gigabytes. Default value is None. - :type quota: int - :param access_tier: Specifies the access tier of the share. Known values are: - "TransactionOptimized", "Hot", "Cool", and "Premium". Default value is None. - :type access_tier: str or ~azure.storage.fileshare.models.ShareAccessTier - :param root_squash: Root squash to set on the share. Only valid for NFS shares. Known values - are: "NoRootSquash", "RootSquash", and "AllSquash". Default value is None. - :type root_squash: str or ~azure.storage.fileshare.models.ShareRootSquash - :param enable_snapshot_virtual_directory_access: Default value is None. - :type enable_snapshot_virtual_directory_access: bool - :param paid_bursting_enabled: Optional. Boolean. Default if not specified is false. This - property enables paid bursting. Default value is None. - :type paid_bursting_enabled: bool - :param paid_bursting_max_bandwidth_mibps: Optional. Integer. Default if not specified is the - maximum throughput the file share can support. Current maximum for a file share is 10,340 - MiB/sec. Default value is None. - :type paid_bursting_max_bandwidth_mibps: int - :param paid_bursting_max_iops: Optional. Integer. Default if not specified is the maximum IOPS - the file share can support. Current maximum for a file share is 102,400 IOPS. Default value is - None. - :type paid_bursting_max_iops: int - :param share_provisioned_iops: Optional. Supported in version 2025-01-05 and later. Only - allowed for provisioned v2 file shares. Specifies the provisioned number of input/output - operations per second (IOPS) of the share. If this is not specified, the provisioned IOPS is - set to value calculated based on recommendation formula. Default value is None. - :type share_provisioned_iops: int - :param share_provisioned_bandwidth_mibps: Optional. Supported in version 2025-01-05 and later. - Only allowed for provisioned v2 file shares. Specifies the provisioned bandwidth of the share, - in mebibytes per second (MiBps). If this is not specified, the provisioned bandwidth is set to - value calculated based on recommendation formula. Default value is None. - :type share_provisioned_bandwidth_mibps: int - :param enable_smb_directory_lease: SMB only, default is true. Specifies whether granting of - new directory leases for directories present in a share are to be enabled or disabled. An input - of true specifies that granting of new directory leases is to be allowed. An input of false - specifies that granting of new directory leases is to be blocked. Default value is None. - :type enable_smb_directory_lease: bool - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["properties"] = kwargs.pop("comp", _params.pop("comp", "properties")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_set_properties_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - quota=quota, - access_tier=access_tier, - lease_id=_lease_id, - root_squash=root_squash, - enable_snapshot_virtual_directory_access=enable_snapshot_virtual_directory_access, - paid_bursting_enabled=paid_bursting_enabled, - paid_bursting_max_bandwidth_mibps=paid_bursting_max_bandwidth_mibps, - paid_bursting_max_iops=paid_bursting_max_iops, - share_provisioned_iops=share_provisioned_iops, - share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, - enable_smb_directory_lease=enable_smb_directory_lease, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) - response_headers["x-ms-share-provisioned-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-iops") - ) - response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") - ) - response_headers["x-ms-share-included-burst-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-included-burst-iops") - ) - response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") - ) - response_headers["x-ms-share-next-allowed-quota-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-quota-downgrade-time") - ) - response_headers["x-ms-share-next-allowed-provisioned-iops-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-iops-downgrade-time") - ) - response_headers["x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time"] = self._deserialize( - "rfc-1123", response.headers.get("x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def set_metadata( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> None: - """Sets one or more user-defined name-value pairs for the specified share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param metadata: A name-value pair to associate with a file storage object. Default value is - None. - :type metadata: dict[str, str] - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["metadata"] = kwargs.pop("comp", _params.pop("comp", "metadata")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_set_metadata_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - metadata=metadata, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_access_policy( - self, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> list[_models.SignedIdentifier]: - """Returns information about stored access policies specified on the share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: list of SignedIdentifier or the result of cls(response) - :rtype: list[~azure.storage.fileshare.models.SignedIdentifier] - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - cls: ClsType[list[_models.SignedIdentifier]] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_access_policy_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("[SignedIdentifier]", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def set_access_policy( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - share_acl: Optional[list[_models.SignedIdentifier]] = None, - **kwargs: Any - ) -> None: - """Sets a stored access policy for use with shared access signatures. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :param share_acl: The ACL for the share. Default value is None. - :type share_acl: list[~azure.storage.fileshare.models.SignedIdentifier] - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["acl"] = kwargs.pop("comp", _params.pop("comp", "acl")) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) - content_type = content_type if share_acl else None - cls: ClsType[None] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - serialization_ctxt = {"xml": {"name": "SignedIdentifiers", "wrapped": True}} - if share_acl is not None: - _content = self._serialize.body( - share_acl, "[SignedIdentifier]", is_xml=True, serialization_ctxt=serialization_ctxt - ) - else: - _content = None - - _request = build_set_access_policy_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - content_type=content_type, - content=_content, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore - - @distributed_trace - def get_statistics( - self, - timeout: Optional[int] = None, - lease_access_conditions: Optional[_models.LeaseAccessConditions] = None, - **kwargs: Any - ) -> _models.ShareStats: - """Retrieves statistics related to the share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param lease_access_conditions: Parameter group. Default value is None. - :type lease_access_conditions: ~azure.storage.fileshare.models.LeaseAccessConditions - :return: ShareStats or the result of cls(response) - :rtype: ~azure.storage.fileshare.models.ShareStats - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["stats"] = kwargs.pop("comp", _params.pop("comp", "stats")) - cls: ClsType[_models.ShareStats] = kwargs.pop("cls", None) - - _lease_id = None - if lease_access_conditions is not None: - _lease_id = lease_access_conditions.lease_id - - _request = build_get_statistics_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - lease_id=_lease_id, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - - deserialized = self._deserialize("ShareStats", pipeline_response.http_response) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def restore( # pylint: disable=inconsistent-return-statements - self, - timeout: Optional[int] = None, - request_id_parameter: Optional[str] = None, - deleted_share_name: Optional[str] = None, - deleted_share_version: Optional[str] = None, - **kwargs: Any - ) -> None: - """Restores a previously deleted Share. - - :param timeout: The timeout parameter is expressed in seconds. For more information, see - :code:`Setting - Timeouts for File Service Operations.`. Default value is None. - :type timeout: int - :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character - limit that is recorded in the analytics logs when storage analytics logging is enabled. Default - value is None. - :type request_id_parameter: str - :param deleted_share_name: Specifies the name of the previously-deleted share. Default value is - None. - :type deleted_share_name: str - :param deleted_share_version: Specifies the version of the previously-deleted share. Default - value is None. - :type deleted_share_version: str - :return: None or the result of cls(response) - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - restype: Literal["share"] = kwargs.pop("restype", _params.pop("restype", "share")) - comp: Literal["undelete"] = kwargs.pop("comp", _params.pop("comp", "undelete")) - cls: ClsType[None] = kwargs.pop("cls", None) - - _request = build_restore_request( - url=self._config.url, - version=self._config.version, - timeout=timeout, - request_id_parameter=request_id_parameter, - deleted_share_name=deleted_share_name, - deleted_share_version=deleted_share_version, - file_request_intent=self._config.file_request_intent, - restype=restype, - comp=comp, - headers=_headers, - params=_params, - ) - _request.url = self._client.format_url(_request.url) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [201]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = self._deserialize.failsafe_deserialize( - _models.StorageError, - pipeline_response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - response_headers["x-ms-request-id"] = self._deserialize("str", response.headers.get("x-ms-request-id")) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - response_headers["x-ms-version"] = self._deserialize("str", response.headers.get("x-ms-version")) - response_headers["Date"] = self._deserialize("rfc-1123", response.headers.get("Date")) - response_headers["x-ms-share-quota"] = self._deserialize("int", response.headers.get("x-ms-share-quota")) - response_headers["x-ms-share-provisioned-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-iops") - ) - response_headers["x-ms-share-provisioned-bandwidth-mibps"] = self._deserialize( - "int", response.headers.get("x-ms-share-provisioned-bandwidth-mibps") - ) - response_headers["x-ms-share-included-burst-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-included-burst-iops") - ) - response_headers["x-ms-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") - ) - - if cls: - return cls(pipeline_response, None, response_headers) # type: ignore diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_lease.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_lease.py index 6a4450f1f78f..2d2a7e8cfd21 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_lease.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_lease.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -43,18 +44,20 @@ class ShareLeaseClient: # pylint: disable=client-accepts-api-version-keyword This will be `None` if no lease has yet been acquired or modified.""" def __init__( # pylint: disable=missing-client-constructor-parameter-credential, missing-client-constructor-parameter-kwargs - self, client: Union["ShareFileClient", "ShareClient"], - lease_id: Optional[str] = None + self, client: Union["ShareFileClient", "ShareClient"], lease_id: Optional[str] = None ) -> None: self.id = lease_id or str(uuid.uuid4()) self.last_modified = None self.etag = None - if hasattr(client, 'file_name'): + self._file_request_intent = getattr(client, "file_request_intent", None) + if hasattr(client, "file_name"): self._client = client._client.file # type: ignore self._snapshot = None - elif hasattr(client, 'share_name'): + self._allow_trailing_dot = getattr(client, "allow_trailing_dot", None) + elif hasattr(client, "share_name"): self._client = client._client.share self._snapshot = client.snapshot + self._allow_trailing_dot = None else: raise TypeError("Lease must use ShareFileClient or ShareClient.") @@ -90,20 +93,24 @@ def acquire(self, **kwargs: Any) -> None: :rtype: None """ try: - lease_duration = kwargs.pop('lease_duration', -1) + lease_duration = kwargs.pop("lease_duration", -1) if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot + if self._allow_trailing_dot is not None: + kwargs["allow_trailing_dot"] = self._allow_trailing_dot response = self._client.acquire_lease( - timeout=kwargs.pop('timeout', None), - duration=lease_duration, + timeout=kwargs.pop("timeout", None), + lease_duration=lease_duration, proposed_lease_id=self.id, + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - self.id = response.get('lease_id') - self.last_modified = response.get('last_modified') - self.etag = response.get('etag') + self.id = response.get("lease_id") + self.last_modified = response.get("last_modified") + self.etag = response.get("etag") @distributed_trace def renew(self, **kwargs: Any) -> None: @@ -130,15 +137,17 @@ def renew(self, **kwargs: Any) -> None: try: response = self._client.renew_lease( lease_id=self.id, - timeout=kwargs.pop('timeout', None), + timeout=kwargs.pop("timeout", None), sharesnapshot=self._snapshot, + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - self.etag = response.get('etag') - self.id = response.get('lease_id') - self.last_modified = response.get('last_modified') + self.etag = response.get("etag") + self.id = response.get("lease_id") + self.last_modified = response.get("last_modified") @distributed_trace def release(self, **kwargs: Any) -> None: @@ -156,21 +165,25 @@ def release(self, **kwargs: Any) -> None: """ try: if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot + if self._allow_trailing_dot is not None: + kwargs["allow_trailing_dot"] = self._allow_trailing_dot response = self._client.release_lease( lease_id=self.id, - timeout=kwargs.pop('timeout', None), + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - self.etag = response.get('etag') - self.id = response.get('lease_id') - self.last_modified = response.get('last_modified') + self.etag = response.get("etag") + self.id = response.get("lease_id") + self.last_modified = response.get("last_modified") @distributed_trace def change(self, proposed_lease_id: str, **kwargs: Any) -> None: - """ Changes the lease ID of an active lease. A change must include the current lease ID in x-ms-lease-id and + """Changes the lease ID of an active lease. A change must include the current lease ID in x-ms-lease-id and a new lease ID in x-ms-proposed-lease-id. :param str proposed_lease_id: @@ -186,18 +199,22 @@ def change(self, proposed_lease_id: str, **kwargs: Any) -> None: """ try: if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot + if self._allow_trailing_dot is not None: + kwargs["allow_trailing_dot"] = self._allow_trailing_dot response = self._client.change_lease( lease_id=self.id, proposed_lease_id=proposed_lease_id, - timeout=kwargs.pop('timeout', None), + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - self.etag = response.get('etag') - self.id = response.get('lease_id') - self.last_modified = response.get('last_modified') + self.etag = response.get("etag") + self.id = response.get("lease_id") + self.last_modified = response.get("last_modified") @distributed_trace def break_lease(self, **kwargs: Any) -> int: @@ -232,18 +249,23 @@ def break_lease(self, **kwargs: Any) -> int: :rtype: int """ try: - lease_break_period = kwargs.pop('lease_break_period', None) + lease_break_period = kwargs.pop("lease_break_period", None) if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot if isinstance(self._client, ShareOperations): - kwargs['break_period'] = lease_break_period + kwargs["break_period"] = lease_break_period if isinstance(self._client, FileOperations) and lease_break_period: raise TypeError("Setting a lease break period is only applicable to Share leases.") + if self._allow_trailing_dot is not None: + kwargs["allow_trailing_dot"] = self._allow_trailing_dot + response = self._client.break_lease( - timeout=kwargs.pop('timeout', None), + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - return cast(int, response.get('lease_time')) + return cast(int, response.get("lease_time")) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_models.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_models.py index c3e709e0867a..a8a7454c615c 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_models.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_models.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -6,10 +7,7 @@ # pylint: disable=too-few-public-methods, too-many-instance-attributes, super-init-not-called, too-many-lines from enum import Enum -from typing import ( - Any, Callable, Dict, List, Literal, Optional, Union, - TYPE_CHECKING -) +from typing import Any, Callable, Dict, List, Literal, Optional, Union, TYPE_CHECKING from urllib.parse import unquote from typing_extensions import Self @@ -40,8 +38,8 @@ def _wrap_item(item): if isinstance(item, DirectoryItem): - return {'name': item.name, 'is_directory': True} - return {'name': item.name, 'size': item.properties.content_length, 'is_directory': False} + return {"name": item.name, "is_directory": True} + return {"name": item.name, "size": item.properties.content_length, "is_directory": False} class RetentionPolicy(GeneratedRetentionPolicy): @@ -95,7 +93,7 @@ class Metrics(GeneratedMetrics): Determines how long the associated data should persist. """ - version: str = '1.0' + version: str = "1.0" """The version of Storage Analytics to configure.""" enabled: bool = False """Indicates whether metrics are enabled for the File service.""" @@ -105,10 +103,10 @@ class Metrics(GeneratedMetrics): """Determines how long the associated data should persist.""" def __init__(self, **kwargs: Any) -> None: - self.version = kwargs.get('version', '1.0') - self.enabled = kwargs.get('enabled', False) - self.include_apis = kwargs.get('include_apis') # type: ignore [assignment] - self.retention_policy = kwargs.get('retention_policy') or RetentionPolicy() + self.version = kwargs.get("version", "1.0") + self.enabled = kwargs.get("enabled", False) + self.include_apis = kwargs.get("include_apis") # type: ignore [assignment] + self.retention_policy = kwargs.get("retention_policy") or RetentionPolicy() @classmethod def _from_generated(cls, generated): @@ -118,7 +116,9 @@ def _from_generated(cls, generated): version=generated.version, enabled=generated.enabled, include_apis=generated.include_apis, - retention_policy=RetentionPolicy._from_generated(generated.retention_policy) # pylint: disable=protected-access + retention_policy=RetentionPolicy._from_generated( # pylint: disable=protected-access + generated.retention_policy + ), ) @@ -168,11 +168,11 @@ class CorsRule(GeneratedCorsRule): """The number of seconds that the client/browser should cache a pre-flight response.""" def __init__(self, allowed_origins: List[str], allowed_methods: List[str], **kwargs: Any) -> None: - self.allowed_origins = ','.join(allowed_origins) - self.allowed_methods = ','.join(allowed_methods) - self.allowed_headers = ','.join(kwargs.get('allowed_headers', [])) - self.exposed_headers = ','.join(kwargs.get('exposed_headers', [])) - self.max_age_in_seconds = kwargs.get('max_age_in_seconds', 0) + self.allowed_origins = ",".join(allowed_origins) + self.allowed_methods = ",".join(allowed_methods) + self.allowed_headers = ",".join(kwargs.get("allowed_headers", [])) + self.exposed_headers = ",".join(kwargs.get("exposed_headers", [])) + self.max_age_in_seconds = kwargs.get("max_age_in_seconds", 0) @staticmethod def _to_generated(rules: Optional[List["CorsRule"]]) -> Optional[List[GeneratedCorsRule]]: @@ -212,7 +212,7 @@ class SmbMultichannel(GeneratedSmbMultichannel): enabled: bool """If SMB Multichannel is enabled.""" - def __init__(self, *, enabled: bool, **kwargs: Any) -> None: + def __init__(self, *, enabled: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument self.enabled = enabled @@ -225,7 +225,7 @@ class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): required: bool """If encryption in transit is enabled.""" - def __init__(self, *, required: bool, **kwargs: Any) -> None: + def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument self.required = required @@ -241,7 +241,7 @@ class ShareSmbSettings(GeneratedShareSmbSettings): encryption_in_transit: Optional[SmbEncryptionInTransit] """Sets the encryption in transit settings.""" - def __init__( + def __init__( # pylint: disable=unused-argument self, *, multichannel: Optional[SmbMultichannel] = None, @@ -263,7 +263,7 @@ class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): required: bool """If encryption in transit is enabled.""" - def __init__(self, *, required: bool, **kwargs: Any) -> None: + def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument self.required = required @@ -276,7 +276,9 @@ class ShareNfsSettings(GeneratedShareNfsSettings): encryption_in_transit: NfsEncryptionInTransit """Sets the encryption in transit settings.""" - def __init__(self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any) -> None: + def __init__( # pylint: disable=unused-argument + self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any + ) -> None: self.encryption_in_transit = encryption_in_transit @@ -294,12 +296,8 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): nfs: Optional[ShareNfsSettings] """Sets the NFS settings.""" - def __init__( - self, - *, - smb: Optional[ShareSmbSettings] = None, - nfs: Optional[ShareNfsSettings] = None, - **kwargs: Any + def __init__( # pylint: disable=unused-argument + self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any ) -> None: self.smb = smb self.nfs = nfs @@ -346,22 +344,20 @@ class ShareSasPermissions: """The create permission for share SAS.""" def __init__( - self, read: bool = False, - write: bool = False, - delete: bool = False, - list: bool = False, - create: bool = False + self, read: bool = False, write: bool = False, delete: bool = False, list: bool = False, create: bool = False ) -> None: self.read = read self.create = create self.write = write self.delete = delete self.list = list - self._str = (('r' if self.read else '') + - ('c' if self.create else '') + - ('w' if self.write else '') + - ('d' if self.delete else '') + - ('l' if self.list else '')) + self._str = ( + ("r" if self.read else "") + + ("c" if self.create else "") + + ("w" if self.write else "") + + ("d" if self.delete else "") + + ("l" if self.list else "") + ) def __str__(self) -> str: return self._str @@ -379,11 +375,11 @@ def from_string(cls, permission: str) -> Self: :return: A ShareSasPermissions object :rtype: ~azure.storage.fileshare.ShareSasPermissions """ - p_read = 'r' in permission - p_create = 'c' in permission - p_write = 'w' in permission - p_delete = 'd' in permission - p_list = 'l' in permission + p_read = "r" in permission + p_create = "c" in permission + p_write = "w" in permission + p_delete = "d" in permission + p_list = "l" in permission parsed = cls(p_read, p_write, p_delete, p_list, p_create) @@ -443,9 +439,10 @@ class AccessPolicy(GenAccessPolicy): """The time at which the shared access signature becomes valid.""" def __init__( - self, permission: Optional[Union[ShareSasPermissions, str]] = None, + self, + permission: Optional[Union[ShareSasPermissions, str]] = None, expiry: Optional[Union["datetime", str]] = None, - start: Optional[Union["datetime", str]] = None + start: Optional[Union["datetime", str]] = None, ) -> None: self.start = start self.expiry = expiry @@ -463,9 +460,9 @@ class LeaseProperties(DictMixin): """When a file or share is leased, specifies whether the lease is of infinite or fixed duration.""" def __init__(self, **kwargs: Any) -> None: - self.status = get_enum_value(kwargs.get('x-ms-lease-status')) - self.state = get_enum_value(kwargs.get('x-ms-lease-state')) - self.duration = get_enum_value(kwargs.get('x-ms-lease-duration')) + self.status = get_enum_value(kwargs.get("x-ms-lease-status")) + self.state = get_enum_value(kwargs.get("x-ms-lease-state")) + self.duration = get_enum_value(kwargs.get("x-ms-lease-duration")) @classmethod def _from_generated(cls, generated): @@ -516,7 +513,8 @@ class ContentSettings(DictMixin): """The content md5 specified for the file.""" def __init__( - self, content_type: Optional[str] = None, + self, + content_type: Optional[str] = None, content_encoding: Optional[str] = None, content_language: Optional[str] = None, content_disposition: Optional[str] = None, @@ -524,12 +522,12 @@ def __init__( content_md5: Optional[bytearray] = None, **kwargs: Any ) -> None: - self.content_type = content_type or kwargs.get('Content-Type') - self.content_encoding = content_encoding or kwargs.get('Content-Encoding') - self.content_language = content_language or kwargs.get('Content-Language') - self.content_md5 = content_md5 or kwargs.get('Content-MD5') - self.content_disposition = content_disposition or kwargs.get('Content-Disposition') - self.cache_control = cache_control or kwargs.get('Cache-Control') + self.content_type = content_type or kwargs.get("Content-Type") + self.content_encoding = content_encoding or kwargs.get("Content-Encoding") + self.content_language = content_language or kwargs.get("Content-Language") + self.content_md5 = content_md5 or kwargs.get("Content-MD5") + self.content_disposition = content_disposition or kwargs.get("Content-Disposition") + self.cache_control = cache_control or kwargs.get("Cache-Control") @classmethod def _from_generated(cls, generated): @@ -604,39 +602,40 @@ class ShareProperties(DictMixin): def __init__(self, **kwargs: Any) -> None: self.name = None # type: ignore [assignment] - self.last_modified = kwargs.get('Last-Modified') # type: ignore [assignment] - self.etag = kwargs.get('ETag') # type: ignore [assignment] - self.quota = kwargs.get('x-ms-share-quota') # type: ignore [assignment] - self.access_tier = kwargs.get('x-ms-access-tier') # type: ignore [assignment] - self.next_allowed_quota_downgrade_time = kwargs.get('x-ms-share-next-allowed-quota-downgrade-time') - self.metadata = kwargs.get('metadata') # type: ignore [assignment] + self.last_modified = kwargs.get("Last-Modified") # type: ignore [assignment] + self.etag = kwargs.get("ETag") # type: ignore [assignment] + self.quota = kwargs.get("x-ms-share-quota") # type: ignore [assignment] + self.access_tier = kwargs.get("x-ms-access-tier") # type: ignore [assignment] + self.next_allowed_quota_downgrade_time = kwargs.get("x-ms-share-next-allowed-quota-downgrade-time") + self.metadata = kwargs.get("metadata") # type: ignore [assignment] self.snapshot = None self.deleted = None self.deleted_time = None self.version = None self.remaining_retention_days = None - self.provisioned_egress_mbps = kwargs.get('x-ms-share-provisioned-egress-mbps') - self.provisioned_ingress_mbps = kwargs.get('x-ms-share-provisioned-ingress-mbps') - self.provisioned_iops = kwargs.get('x-ms-share-provisioned-iops') - self.provisioned_bandwidth = kwargs.get('x-ms-share-provisioned-bandwidth-mibps') + self.provisioned_egress_mbps = kwargs.get("x-ms-share-provisioned-egress-mbps") + self.provisioned_ingress_mbps = kwargs.get("x-ms-share-provisioned-ingress-mbps") + self.provisioned_iops = kwargs.get("x-ms-share-provisioned-iops") + self.provisioned_bandwidth = kwargs.get("x-ms-share-provisioned-bandwidth-mibps") self.lease = LeaseProperties(**kwargs) enabled_protocols = kwargs.get("x-ms-enabled-protocols", None) if enabled_protocols is not None: - self.protocols = [protocol.strip() for protocol in enabled_protocols.split(',')] + self.protocols = [protocol.strip() for protocol in enabled_protocols.split(",")] else: self.protocols = None - self.root_squash = kwargs.get('x-ms-root-squash', None) - self.enable_snapshot_virtual_directory_access = \ - kwargs.get('x-ms-enable-snapshot-virtual-directory-access') - self.paid_bursting_enabled = kwargs.get('x-ms-share-paid-bursting-enabled') - self.paid_bursting_bandwidth_mibps = kwargs.get('x-ms-share-paid-bursting-max-bandwidth-mibps') - self.paid_bursting_iops = kwargs.get('x-ms-share-paid-bursting-max-iops') - self.included_burst_iops = kwargs.get('x-ms-share-included-burst-iops') - self.max_burst_credits_for_iops = kwargs.get('x-ms-share-max-burst-credits-for-iops') - self.next_provisioned_iops_downgrade = ( # pylint: disable=name-too-long - kwargs.get('x-ms-share-next-allowed-provisioned-iops-downgrade-time')) - self.next_provisioned_bandwidth_downgrade = ( # pylint: disable=name-too-long - kwargs.get('x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time')) + self.root_squash = kwargs.get("x-ms-root-squash", None) + self.enable_snapshot_virtual_directory_access = kwargs.get("x-ms-enable-snapshot-virtual-directory-access") + self.paid_bursting_enabled = kwargs.get("x-ms-share-paid-bursting-enabled") + self.paid_bursting_bandwidth_mibps = kwargs.get("x-ms-share-paid-bursting-max-bandwidth-mibps") + self.paid_bursting_iops = kwargs.get("x-ms-share-paid-bursting-max-iops") + self.included_burst_iops = kwargs.get("x-ms-share-included-burst-iops") + self.max_burst_credits_for_iops = kwargs.get("x-ms-share-max-burst-credits-for-iops") + self.next_provisioned_iops_downgrade = kwargs.get( # pylint: disable=name-too-long + "x-ms-share-next-allowed-provisioned-iops-downgrade-time" + ) + self.next_provisioned_bandwidth_downgrade = kwargs.get( # pylint: disable=name-too-long + "x-ms-share-next-allowed-provisioned-bandwidth-downgrade-time" + ) @classmethod def _from_generated(cls, generated): @@ -658,8 +657,11 @@ def _from_generated(cls, generated): props.provisioned_iops = generated.properties.provisioned_iops props.provisioned_bandwidth = generated.properties.provisioned_bandwidth_mi_bps props.lease = LeaseProperties._from_generated(generated) # pylint: disable=protected-access - props.protocols = [protocol.strip() for protocol in generated.properties.enabled_protocols.split(',')]\ - if generated.properties.enabled_protocols else None + props.protocols = ( + [protocol.strip() for protocol in generated.properties.enabled_protocols.split(",")] + if generated.properties.enabled_protocols + else None + ) props.root_squash = generated.properties.root_squash props.enable_snapshot_virtual_directory_access = generated.properties.enable_snapshot_virtual_directory_access props.paid_bursting_enabled = generated.properties.paid_bursting_enabled @@ -668,9 +670,11 @@ def _from_generated(cls, generated): props.included_burst_iops = generated.properties.included_burst_iops props.max_burst_credits_for_iops = generated.properties.max_burst_credits_for_iops props.next_provisioned_iops_downgrade = ( # pylint: disable=name-too-long - generated.properties.next_allowed_provisioned_iops_downgrade_time) + generated.properties.next_allowed_provisioned_iops_downgrade_time + ) props.next_provisioned_bandwidth_downgrade = ( # pylint: disable=name-too-long - generated.properties.next_allowed_provisioned_bandwidth_downgrade_time) + generated.properties.next_allowed_provisioned_bandwidth_downgrade_time + ) return props @@ -699,15 +703,14 @@ class SharePropertiesPaged(PageIterator): """The current page of listed results.""" def __init__( - self, command: Callable, + self, + command: Callable, prefix: Optional[str] = None, results_per_page: Optional[int] = None, - continuation_token: Optional[str] = None + continuation_token: Optional[str] = None, ) -> None: super(SharePropertiesPaged, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token or "" + get_next=self._get_next_cb, extract_data=self._extract_data_cb, continuation_token=continuation_token or "" ) self._command = command self.service_endpoint = None @@ -724,7 +727,8 @@ def _get_next_cb(self, continuation_token): maxresults=self.results_per_page, prefix=self.prefix, cls=return_context_and_deserialized, - use_location=self.location_mode) + use_location=self.location_mode, + ) except HttpResponseError as error: process_storage_error(error) @@ -734,7 +738,9 @@ def _extract_data_cb(self, get_next_return): self.prefix = self._response.prefix self.marker = self._response.marker self.results_per_page = self._response.max_results - self.current_page = [ShareProperties._from_generated(i) for i in self._response.share_items] # pylint: disable=protected-access + self.current_page = [ + ShareProperties._from_generated(i) for i in self._response.share_items # pylint: disable=protected-access + ] return self._response.next_marker or None, self.current_page @@ -775,20 +781,20 @@ class Handle(DictMixin): """Time when the session that previously opened the handle was last been reconnected. (UTC)""" last_reconnect_time: Optional["datetime"] """Time handle that was last connected to. (UTC)""" - access_rights: List[Literal['Read', 'Write', 'Delete']] + access_rights: List[Literal["Read", "Write", "Delete"]] """Access rights of the handle.""" def __init__(self, **kwargs: Any) -> None: - self.client_name = kwargs.get('client_name') # type: ignore [assignment] - self.id = kwargs.get('handle_id') # type: ignore [assignment] - self.path = kwargs.get('path') # type: ignore [assignment] - self.file_id = kwargs.get('file_id') # type: ignore [assignment] - self.parent_id = kwargs.get('parent_id') # type: ignore [assignment] - self.session_id = kwargs.get('session_id') # type: ignore [assignment] - self.client_ip = kwargs.get('client_ip') # type: ignore [assignment] - self.open_time = kwargs.get('open_time') # type: ignore [assignment] - self.last_reconnect_time = kwargs.get('last_reconnect_time') - self.access_rights = kwargs.get('access_right_list') # type: ignore [assignment] + self.client_name = kwargs.get("client_name") # type: ignore [assignment] + self.id = kwargs.get("handle_id") # type: ignore [assignment] + self.path = kwargs.get("path") # type: ignore [assignment] + self.file_id = kwargs.get("file_id") # type: ignore [assignment] + self.parent_id = kwargs.get("parent_id") # type: ignore [assignment] + self.session_id = kwargs.get("session_id") # type: ignore [assignment] + self.client_ip = kwargs.get("client_ip") # type: ignore [assignment] + self.open_time = kwargs.get("open_time") # type: ignore [assignment] + self.last_reconnect_time = kwargs.get("last_reconnect_time") + self.access_rights = kwargs.get("access_right_list") # type: ignore [assignment] @classmethod def _from_generated(cls, generated): @@ -825,14 +831,10 @@ class HandlesPaged(PageIterator): """The current page of listed results.""" def __init__( - self, command: Callable, - results_per_page: Optional[int] = None, - continuation_token: Optional[str] = None + self, command: Callable, results_per_page: Optional[int] = None, continuation_token: Optional[str] = None ) -> None: super(HandlesPaged, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token or "" + get_next=self._get_next_cb, extract_data=self._extract_data_cb, continuation_token=continuation_token or "" ) self._command = command self.marker = None @@ -846,13 +848,16 @@ def _get_next_cb(self, continuation_token): marker=continuation_token or None, maxresults=self.results_per_page, cls=return_context_and_deserialized, - use_location=self.location_mode) + use_location=self.location_mode, + ) except HttpResponseError as error: process_storage_error(error) def _extract_data_cb(self, get_next_return): self.location_mode, self._response = get_next_return - self.current_page = [Handle._from_generated(h) for h in self._response.handle_list] # pylint: disable=protected-access + self.current_page = [ + Handle._from_generated(h) for h in self._response.handle_list # pylint: disable=protected-access + ] return self._response.next_marker or None, self.current_page @@ -884,7 +889,8 @@ class NTFSAttributes: """Enable/disable 'NoScrubData' attribute for DIRECTORY.""" def __init__( - self, read_only: bool = False, + self, + read_only: bool = False, hidden: bool = False, system: bool = False, none: bool = False, @@ -893,7 +899,7 @@ def __init__( temporary: bool = False, offline: bool = False, not_content_indexed: bool = False, - no_scrub_data: bool = False + no_scrub_data: bool = False, ) -> None: self.read_only = read_only self.hidden = hidden @@ -905,20 +911,22 @@ def __init__( self.offline = offline self.not_content_indexed = not_content_indexed self.no_scrub_data = no_scrub_data - self._str = (('ReadOnly|' if self.read_only else '') + - ('Hidden|' if self.hidden else '') + - ('System|' if self.system else '') + - ('None|' if self.none else '') + - ('Directory|' if self.directory else '') + - ('Archive|' if self.archive else '') + - ('Temporary|' if self.temporary else '') + - ('Offline|' if self.offline else '') + - ('NotContentIndexed|' if self.not_content_indexed else '') + - ('NoScrubData|' if self.no_scrub_data else '')) + self._str = ( + ("ReadOnly|" if self.read_only else "") + + ("Hidden|" if self.hidden else "") + + ("System|" if self.system else "") + + ("None|" if self.none else "") + + ("Directory|" if self.directory else "") + + ("Archive|" if self.archive else "") + + ("Temporary|" if self.temporary else "") + + ("Offline|" if self.offline else "") + + ("NotContentIndexed|" if self.not_content_indexed else "") + + ("NoScrubData|" if self.no_scrub_data else "") + ) def __str__(self): concatenated_params = self._str - return concatenated_params.strip('|') + return concatenated_params.strip("|") @classmethod def from_string(cls, string: str) -> Self: @@ -942,8 +950,9 @@ def from_string(cls, string: str) -> Self: not_content_indexed = "NotContentIndexed" in string no_scrub_data = "NoScrubData" in string - parsed = cls(read_only, hidden, system, none, directory, archive, temporary, offline, not_content_indexed, - no_scrub_data) + parsed = cls( + read_only, hidden, system, none, directory, archive, temporary, offline, not_content_indexed, no_scrub_data + ) parsed._str = string return parsed @@ -985,31 +994,40 @@ class DirectoryProperties(DictMixin): """NFS only. The owning group of the directory.""" file_mode: Optional[str] = None """NFS only. The file mode of the directory.""" - nfs_file_type: Optional[Literal['Directory']] = None + nfs_file_type: Optional[Literal["Directory"]] = None """NFS only. The type of the directory.""" def __init__(self, **kwargs: Any) -> None: self.name = None # type: ignore [assignment] - self.last_modified = kwargs.get('Last-Modified') # type: ignore [assignment] - self.etag = kwargs.get('ETag') # type: ignore [assignment] - self.server_encrypted = kwargs.get('x-ms-server-encrypted') # type: ignore [assignment] - self.metadata = kwargs.get('metadata') # type: ignore [assignment] - self.change_time = Deserializer.deserialize_iso(kwargs.get('x-ms-file-change-time')) if ( - kwargs.get('x-ms-file-change-time') is not None) else None - self.creation_time = Deserializer.deserialize_iso(kwargs.get('x-ms-file-creation-time')) if ( - kwargs.get('x-ms-file-creation-time') is not None) else None - self.last_write_time = Deserializer.deserialize_iso(kwargs.get('x-ms-file-last-write-time')) if ( - kwargs.get('x-ms-file-last-write-time') is not None) else None + self.last_modified = kwargs.get("Last-Modified") # type: ignore [assignment] + self.etag = kwargs.get("ETag") # type: ignore [assignment] + self.server_encrypted = kwargs.get("x-ms-server-encrypted") # type: ignore [assignment] + self.metadata = kwargs.get("metadata") # type: ignore [assignment] + self.change_time = ( + Deserializer.deserialize_iso(kwargs.get("x-ms-file-change-time")) + if (kwargs.get("x-ms-file-change-time") is not None) + else None + ) + self.creation_time = ( + Deserializer.deserialize_iso(kwargs.get("x-ms-file-creation-time")) + if (kwargs.get("x-ms-file-creation-time") is not None) + else None + ) + self.last_write_time = ( + Deserializer.deserialize_iso(kwargs.get("x-ms-file-last-write-time")) + if (kwargs.get("x-ms-file-last-write-time") is not None) + else None + ) self.last_access_time = None - self.file_attributes = kwargs.get('x-ms-file-attributes') # type: ignore [assignment] - self.permission_key = kwargs.get('x-ms-file-permission-key') # type: ignore [assignment] - self.file_id = kwargs.get('x-ms-file-id') # type: ignore [assignment] - self.parent_id = kwargs.get('x-ms-file-parent-id') # type: ignore [assignment] + self.file_attributes = kwargs.get("x-ms-file-attributes") # type: ignore [assignment] + self.permission_key = kwargs.get("x-ms-file-permission-key") # type: ignore [assignment] + self.file_id = kwargs.get("x-ms-file-id") # type: ignore [assignment] + self.parent_id = kwargs.get("x-ms-file-parent-id") # type: ignore [assignment] self.is_directory = True - self.owner = kwargs.get('x-ms-owner') - self.group = kwargs.get('x-ms-group') - self.file_mode = kwargs.get('x-ms-mode') - self.nfs_file_type = kwargs.get('x-ms-file-file-type') + self.owner = kwargs.get("x-ms-owner") + self.group = kwargs.get("x-ms-group") + self.file_mode = kwargs.get("x-ms-mode") + self.nfs_file_type = kwargs.get("x-ms-file-file-type") @classmethod def _from_generated(cls, generated): @@ -1057,15 +1075,14 @@ class DirectoryPropertiesPaged(PageIterator): """The current page of listed results.""" def __init__( - self, command: Callable, + self, + command: Callable, prefix: Optional[str] = None, results_per_page: Optional[int] = None, - continuation_token: Optional[str] = None + continuation_token: Optional[str] = None, ) -> None: super(DirectoryPropertiesPaged, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token or "" + get_next=self._get_next_cb, extract_data=self._extract_data_cb, continuation_token=continuation_token or "" ) self._command = command self.service_endpoint = None @@ -1082,17 +1099,20 @@ def _get_next_cb(self, continuation_token): prefix=self.prefix, maxresults=self.results_per_page, cls=return_context_and_deserialized, - use_location=self.location_mode) + use_location=self.location_mode, + ) except HttpResponseError as error: process_storage_error(error) def _extract_data_cb(self, get_next_return): + # pylint: disable=protected-access self.location_mode, self._response = get_next_return self.service_endpoint = self._response.service_endpoint self.marker = self._response.marker self.results_per_page = self._response.max_results - self.current_page = [DirectoryProperties._from_generated(i) for i in self._response.segment.directory_items] # pylint: disable = protected-access - self.current_page.extend([FileProperties._from_generated(i) for i in self._response.segment.file_items]) # pylint: disable = protected-access + self.current_page = [DirectoryProperties._from_generated(i) for i in self._response.segment.directory_items] + self.current_page.extend([FileProperties._from_generated(i) for i in self._response.segment.file_items]) + # pylint: enable=protected-access return self._response.next_marker or None, self.current_page @@ -1143,14 +1163,14 @@ class CopyProperties(DictMixin): failed copy attempt.""" def __init__(self, **kwargs: Any) -> None: - self.id = kwargs.get('x-ms-copy-id') # type: ignore [assignment] - self.source = kwargs.get('x-ms-copy-source') - self.status = get_enum_value(kwargs.get('x-ms-copy-status')) - self.progress = kwargs.get('x-ms-copy-progress') - self.completion_time = kwargs.get('x-ms-copy-completion_time') - self.status_description = kwargs.get('x-ms-copy-status-description') - self.incremental_copy = kwargs.get('x-ms-incremental-copy') - self.destination_snapshot = kwargs.get('x-ms-copy-destination-snapshot') + self.id = kwargs.get("x-ms-copy-id") # type: ignore [assignment] + self.source = kwargs.get("x-ms-copy-source") + self.status = get_enum_value(kwargs.get("x-ms-copy-status")) + self.progress = kwargs.get("x-ms-copy-progress") + self.completion_time = kwargs.get("x-ms-copy-completion_time") + self.status_description = kwargs.get("x-ms-copy-status-description") + self.incremental_copy = kwargs.get("x-ms-incremental-copy") + self.destination_snapshot = kwargs.get("x-ms-copy-destination-snapshot") @classmethod def _from_generated(cls, generated): @@ -1226,42 +1246,51 @@ class FileProperties(DictMixin): """NFS only. The file mode of the file.""" link_count: Optional[int] = None """NFS only. The number of hard links of the file.""" - nfs_file_type: Optional[Literal['Regular']] = None + nfs_file_type: Optional[Literal["Regular"]] = None """NFS only. The type of the file.""" def __init__(self, **kwargs: Any) -> None: - self.name = kwargs.get('name') # type: ignore [assignment] + self.name = kwargs.get("name") # type: ignore [assignment] self.path = None self.share = None self.snapshot = None - self.content_length = kwargs.get('Content-Length') # type: ignore [assignment] - self.metadata = kwargs.get('metadata') # type: ignore [assignment] - self.file_type = kwargs.get('x-ms-type') # type: ignore [assignment] - self.last_modified = kwargs.get('Last-Modified') # type: ignore [assignment] - self.etag = kwargs.get('ETag') # type: ignore [assignment] - self.size = kwargs.get('Content-Length') # type: ignore [assignment] - self.content_range = kwargs.get('Content-Range') - self.server_encrypted = kwargs.get('x-ms-server-encrypted') # type: ignore [assignment] + self.content_length = kwargs.get("Content-Length") # type: ignore [assignment] + self.metadata = kwargs.get("metadata") # type: ignore [assignment] + self.file_type = kwargs.get("x-ms-type") # type: ignore [assignment] + self.last_modified = kwargs.get("Last-Modified") # type: ignore [assignment] + self.etag = kwargs.get("ETag") # type: ignore [assignment] + self.size = kwargs.get("Content-Length") # type: ignore [assignment] + self.content_range = kwargs.get("Content-Range") + self.server_encrypted = kwargs.get("x-ms-server-encrypted") # type: ignore [assignment] self.copy = CopyProperties(**kwargs) self.content_settings = ContentSettings(**kwargs) self.lease = LeaseProperties(**kwargs) - self.change_time = Deserializer.deserialize_iso(kwargs.get('x-ms-file-change-time')) if ( - kwargs.get('x-ms-file-change-time') is not None) else None - self.creation_time = Deserializer.deserialize_iso(kwargs.get('x-ms-file-creation-time')) if ( - kwargs.get('x-ms-file-creation-time') is not None) else None - self.last_write_time = Deserializer.deserialize_iso(kwargs.get('x-ms-file-last-write-time')) if ( - kwargs.get('x-ms-file-last-write-time') is not None) else None + self.change_time = ( + Deserializer.deserialize_iso(kwargs.get("x-ms-file-change-time")) + if (kwargs.get("x-ms-file-change-time") is not None) + else None + ) + self.creation_time = ( + Deserializer.deserialize_iso(kwargs.get("x-ms-file-creation-time")) + if (kwargs.get("x-ms-file-creation-time") is not None) + else None + ) + self.last_write_time = ( + Deserializer.deserialize_iso(kwargs.get("x-ms-file-last-write-time")) + if (kwargs.get("x-ms-file-last-write-time") is not None) + else None + ) self.last_access_time = None - self.file_attributes = kwargs.get('x-ms-file-attributes') # type: ignore [assignment] - self.permission_key = kwargs.get('x-ms-file-permission-key') # type: ignore [assignment] - self.file_id = kwargs.get('x-ms-file-id') # type: ignore [assignment] - self.parent_id = kwargs.get('x-ms-file-parent-id') + self.file_attributes = kwargs.get("x-ms-file-attributes") # type: ignore [assignment] + self.permission_key = kwargs.get("x-ms-file-permission-key") # type: ignore [assignment] + self.file_id = kwargs.get("x-ms-file-id") # type: ignore [assignment] + self.parent_id = kwargs.get("x-ms-file-parent-id") self.is_directory = False - self.owner = kwargs.get('x-ms-owner') - self.group = kwargs.get('x-ms-group') - self.file_mode = kwargs.get('x-ms-mode') - self.link_count = kwargs.get('x-ms-link-count') - self.nfs_file_type = kwargs.get('x-ms-file-file-type') + self.owner = kwargs.get("x-ms-owner") + self.group = kwargs.get("x-ms-group") + self.file_mode = kwargs.get("x-ms-mode") + self.link_count = kwargs.get("x-ms-link-count") + self.nfs_file_type = kwargs.get("x-ms-file-file-type") @classmethod def _from_generated(cls, generated): @@ -1282,6 +1311,7 @@ def _from_generated(cls, generated): class ShareProtocols(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Enabled protocols on the share""" + SMB = "SMB" NFS = "NFS" @@ -1311,20 +1341,17 @@ class FileSasPermissions: delete: bool = False """Delete the file.""" - def __init__( - self, read: bool = False, - create: bool = False, - write: bool = False, - delete: bool = False - ) -> None: + def __init__(self, read: bool = False, create: bool = False, write: bool = False, delete: bool = False) -> None: self.read = read self.create = create self.write = write self.delete = delete - self._str = (('r' if self.read else '') + - ('c' if self.create else '') + - ('w' if self.write else '') + - ('d' if self.delete else '')) + self._str = ( + ("r" if self.read else "") + + ("c" if self.create else "") + + ("w" if self.write else "") + + ("d" if self.delete else "") + ) def __str__(self): return self._str @@ -1342,10 +1369,10 @@ def from_string(cls, permission: str) -> Self: :return: A FileSasPermissions object :rtype: ~azure.storage.fileshare.FileSasPermissions """ - p_read = 'r' in permission - p_create = 'c' in permission - p_write = 'w' in permission - p_delete = 'd' in permission + p_read = "r" in permission + p_create = "c" in permission + p_write = "w" in permission + p_delete = "d" in permission parsed = cls(p_read, p_create, p_write, p_delete) @@ -1354,8 +1381,8 @@ def from_string(cls, permission: str) -> Self: def service_properties_deserialize(generated: GeneratedStorageServiceProperties) -> Dict[str, Any]: return { - 'hour_metrics': Metrics._from_generated(generated.hour_metrics), # pylint: disable=protected-access - 'minute_metrics': Metrics._from_generated(generated.minute_metrics), # pylint: disable=protected-access - 'cors': [CorsRule._from_generated(cors) for cors in generated.cors], # type: ignore [union-attr] # pylint: disable=protected-access - 'protocol': ShareProtocolSettings._from_generated(generated.protocol), # pylint: disable=protected-access + "hour_metrics": Metrics._from_generated(generated.hour_metrics), # pylint: disable=protected-access + "minute_metrics": Metrics._from_generated(generated.minute_metrics), # pylint: disable=protected-access + "cors": [CorsRule._from_generated(cors) for cors in generated.cors], # type: ignore [union-attr] # pylint: disable=protected-access + "protocol": ShareProtocolSettings._from_generated(generated.protocol), # pylint: disable=protected-access } diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_parser.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_parser.py index 6b3142cadd82..a1635d1439b4 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_parser.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_parser.py @@ -9,15 +9,16 @@ from ._generated._utils.serialization import Serializer -_ERROR_TOO_MANY_FILE_PERMISSIONS = 'file_permission and file_permission_key should not be set at the same time' -_FILE_PERMISSION_TOO_LONG = 'Size of file_permission is too large. file_permission should be <=8KB, else' \ - 'please use file_permission_key' +_ERROR_TOO_MANY_FILE_PERMISSIONS = "file_permission and file_permission_key should not be set at the same time" +_FILE_PERMISSION_TOO_LONG = ( + "Size of file_permission is too large. file_permission should be <=8KB, else please use file_permission_key" +) def _get_file_permission(file_permission, file_permission_key, default_permission): # if file_permission and file_permission_key are both empty, then use the default_permission # value as file permission, file_permission size should be <= 8KB, else file permission_key should be used - if file_permission and len(str(file_permission).encode('utf-8')) > 8 * 1024: + if file_permission and len(str(file_permission).encode("utf-8")) > 8 * 1024: raise ValueError(_FILE_PERMISSION_TOO_LONG) if not file_permission: @@ -50,11 +51,27 @@ def _datetime_to_str(datetime_obj): def _parse_snapshot( - snapshot: Optional[Union[str, Dict[str, Any]]] = None, - path_snapshot: Optional[str] = None + snapshot: Optional[Union[str, Dict[str, Any]]] = None, path_snapshot: Optional[str] = None ) -> Optional[str]: - if hasattr(snapshot, 'snapshot'): + if hasattr(snapshot, "snapshot"): return snapshot.snapshot # type: ignore if isinstance(snapshot, Dict): - return cast(str, snapshot['snapshot']) + return cast(str, snapshot["snapshot"]) return snapshot or path_snapshot + + +def _strip_snapshot_from_url(url: str) -> str: + """Strip sharesnapshot and snapshot query params from a URL. + + The generated client should receive a base URL without snapshot params, + since snapshots are passed per-operation. + + :param str url: The full URL possibly containing snapshot query params. + :return: The URL with sharesnapshot and snapshot query params removed. + :rtype: str + """ + if "?" not in url: + return url + base, qs = url.split("?", 1) + filtered = "&".join(part for part in qs.split("&") if not part.startswith(("sharesnapshot=", "snapshot="))) + return f"{base}?{filtered}" if filtered else base diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_serialize.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_serialize.py index 6f62fabe6b52..1f362734a901 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_serialize.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_serialize.py @@ -9,13 +9,6 @@ from azure.core import MatchConditions from ._parser import _datetime_to_str, _get_file_permission -from ._generated.models import ( - SourceModifiedAccessConditions, - LeaseAccessConditions, - SourceLeaseAccessConditions, - DestinationLeaseAccessConditions, - CopyFileSmbInfo -) if TYPE_CHECKING: from ._lease import ShareLeaseClient @@ -23,43 +16,41 @@ _SUPPORTED_API_VERSIONS = [ - '2019-02-02', - '2019-07-07', - '2019-10-10', - '2019-12-12', - '2020-02-10', - '2020-04-08', - '2020-06-12', - '2020-08-04', - '2020-10-02', - '2020-12-06', - '2021-02-12', - '2021-04-10', - '2021-06-08', - '2021-08-06', - '2021-12-02', - '2022-11-02', - '2023-01-03', - '2023-05-03', - '2023-08-03', - '2023-11-03', - '2024-05-04', - '2024-08-04', - '2024-11-04', - '2025-01-05', - '2025-05-05', - '2025-07-05', - '2025-11-05', - '2026-02-06', - '2026-04-06', - '2026-06-06', + "2019-02-02", + "2019-07-07", + "2019-10-10", + "2019-12-12", + "2020-02-10", + "2020-04-08", + "2020-06-12", + "2020-08-04", + "2020-10-02", + "2020-12-06", + "2021-02-12", + "2021-04-10", + "2021-06-08", + "2021-08-06", + "2021-12-02", + "2022-11-02", + "2023-01-03", + "2023-05-03", + "2023-08-03", + "2023-11-03", + "2024-05-04", + "2024-08-04", + "2024-11-04", + "2025-01-05", + "2025-05-05", + "2025-07-05", + "2025-11-05", + "2026-02-06", + "2026-04-06", + "2026-06-06", ] def _get_match_headers( - kwargs: Dict[str, Any], - match_param: str, - etag_param: str + kwargs: Dict[str, Any], match_param: str, etag_param: str ) -> Tuple[Optional[str], Optional[str]]: if_match = None if_none_match = None @@ -69,13 +60,13 @@ def _get_match_headers( if not if_match: raise ValueError(f"'{match_param}' specified without '{etag_param}'.") elif match_condition == MatchConditions.IfPresent: - if_match = '*' + if_match = "*" elif match_condition == MatchConditions.IfModified: if_none_match = kwargs.pop(etag_param, None) if not if_none_match: raise ValueError(f"'{match_param}' specified without '{etag_param}'.") elif match_condition == MatchConditions.IfMissing: - if_none_match = '*' + if_none_match = "*" elif match_condition is None: if etag_param in kwargs: raise ValueError(f"'{etag_param}' specified without '{match_param}'.") @@ -84,61 +75,74 @@ def _get_match_headers( return if_match, if_none_match -def get_source_conditions(kwargs: Dict[str, Any]) -> SourceModifiedAccessConditions: - if_match, if_none_match = _get_match_headers(kwargs, 'source_match_condition', 'source_etag') - return SourceModifiedAccessConditions( - source_if_modified_since=kwargs.pop('source_if_modified_since', None), - source_if_unmodified_since=kwargs.pop('source_if_unmodified_since', None), - source_if_match=if_match or kwargs.pop('source_if_match', None), - source_if_none_match=if_none_match or kwargs.pop('source_if_none_match', None) - ) +def get_source_conditions(kwargs: Dict[str, Any]) -> Dict[str, Any]: + if_match, if_none_match = _get_match_headers(kwargs, "source_match_condition", "source_etag") + return { + "source_if_modified_since": kwargs.pop("source_if_modified_since", None), + "source_if_unmodified_since": kwargs.pop("source_if_unmodified_since", None), + "source_if_match": if_match or kwargs.pop("source_if_match", None), + "source_if_none_match": if_none_match or kwargs.pop("source_if_none_match", None), + } -def get_access_conditions( - lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]] -) -> Optional[LeaseAccessConditions]: +def get_access_conditions(lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]]) -> Optional[str]: + """Extract lease_id from a lease client or string. Returns the lease_id string or None. + + :param lease: A lease client or string lease ID. + :type lease: ~azure.storage.fileshare.ShareLeaseClient or str or None + :returns: The lease ID or None. + :rtype: str or None + """ if lease is None: return None if hasattr(lease, "id"): - lease_id = lease.id - else: - lease_id = lease - return LeaseAccessConditions(lease_id=lease_id) + return lease.id + return lease def get_source_access_conditions( lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]] -) -> Optional[SourceLeaseAccessConditions]: +) -> Optional[str]: + """Extract source_lease_id from a lease client or string. Returns the lease_id string or None. + + :param lease: A lease client or string lease ID. + :type lease: ~azure.storage.fileshare.ShareLeaseClient or str or None + :returns: The lease ID or None. + :rtype: str or None + """ if lease is None: return None if hasattr(lease, "id"): - lease_id = lease.id - else: - lease_id = lease - return SourceLeaseAccessConditions(source_lease_id=lease_id) + return lease.id + return lease def get_dest_access_conditions( lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]] -) -> Optional[DestinationLeaseAccessConditions]: +) -> Optional[str]: + """Extract destination_lease_id from a lease client or string. Returns the lease_id string or None. + + :param lease: A lease client or string lease ID. + :type lease: ~azure.storage.fileshare.ShareLeaseClient or str or None + :returns: The lease ID or None. + :rtype: str or None + """ if lease is None: return None if hasattr(lease, "id"): - lease_id = lease.id - else: - lease_id = lease - return DestinationLeaseAccessConditions(destination_lease_id=lease_id) + return lease.id + return lease def get_smb_properties(kwargs: Dict[str, Any]) -> Dict[str, Any]: - ignore_read_only = kwargs.pop('ignore_read_only', None) - set_archive_attribute = kwargs.pop('set_archive_attribute', None) - file_permission = kwargs.pop('file_permission', None) - file_permission_key = kwargs.pop('permission_key', None) - file_attributes = kwargs.pop('file_attributes', None) - file_creation_time = kwargs.pop('file_creation_time', None) - file_last_write_time = kwargs.pop('file_last_write_time', None) - file_change_time = kwargs.pop('file_change_time', None) + ignore_read_only = kwargs.pop("ignore_read_only", None) + set_archive_attribute = kwargs.pop("set_archive_attribute", None) + file_permission = kwargs.pop("file_permission", None) + file_permission_key = kwargs.pop("permission_key", None) + file_attributes = kwargs.pop("file_attributes", None) + file_creation_time = kwargs.pop("file_creation_time", None) + file_last_write_time = kwargs.pop("file_last_write_time", None) + file_change_time = kwargs.pop("file_change_time", None) file_permission_copy_mode = None file_permission = _get_file_permission(file_permission, file_permission_key, None) @@ -156,45 +160,41 @@ def get_smb_properties(kwargs: Dict[str, Any]) -> Dict[str, Any]: else: file_permission_copy_mode = "override" return { - 'file_permission': file_permission, - 'file_permission_key': file_permission_key, - 'copy_file_smb_info': CopyFileSmbInfo( - file_permission_copy_mode=file_permission_copy_mode, - ignore_read_only=ignore_read_only, - file_attributes=file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - set_archive_attribute=set_archive_attribute - ) - + "file_permission": file_permission, + "file_permission_key": file_permission_key, + "file_permission_copy_mode": file_permission_copy_mode, + "ignore_read_only": ignore_read_only, + "file_attributes": file_attributes, + "file_creation_time": _datetime_to_str(file_creation_time), + "file_last_write_time": _datetime_to_str(file_last_write_time), + "file_change_time": _datetime_to_str(file_change_time), + "set_archive_attribute": set_archive_attribute, } def get_rename_smb_properties(kwargs: Dict[str, Any]) -> Dict[str, Any]: - file_permission = kwargs.pop('file_permission', None) - file_permission_key = kwargs.pop('permission_key', None) - file_attributes = kwargs.pop('file_attributes', None) - file_creation_time = kwargs.pop('file_creation_time', None) - file_last_write_time = kwargs.pop('file_last_write_time', None) - file_change_time = kwargs.pop('file_change_time', None) + file_permission = kwargs.pop("file_permission", None) + file_permission_key = kwargs.pop("permission_key", None) + file_attributes = kwargs.pop("file_attributes", None) + file_creation_time = kwargs.pop("file_creation_time", None) + file_last_write_time = kwargs.pop("file_last_write_time", None) + file_change_time = kwargs.pop("file_change_time", None) file_permission = _get_file_permission(file_permission, file_permission_key, None) return { - 'file_permission': file_permission, - 'file_permission_key': file_permission_key, - 'copy_file_smb_info': CopyFileSmbInfo( - file_attributes=file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time) - )} + "file_permission": file_permission, + "file_permission_key": file_permission_key, + "file_attributes": file_attributes, + "file_creation_time": _datetime_to_str(file_creation_time), + "file_last_write_time": _datetime_to_str(file_last_write_time), + "file_change_time": _datetime_to_str(file_change_time), + } def get_api_version(kwargs: Dict[str, Any]) -> str: - api_version = kwargs.get('api_version', None) + api_version = kwargs.get("api_version", None) if api_version and api_version not in _SUPPORTED_API_VERSIONS: - versions = '\n'.join(_SUPPORTED_API_VERSIONS) + versions = "\n".join(_SUPPORTED_API_VERSIONS) raise ValueError(f"Unsupported API version '{api_version}'. Please select from:\n{versions}") return api_version or _SUPPORTED_API_VERSIONS[-1] diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client.py index f5815256d02a..d4398fa4c4e6 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -5,10 +6,7 @@ # -------------------------------------------------------------------------- # pylint: disable=docstring-keyword-should-match-keyword-only -from typing import ( - Any, cast, Dict, Literal, Optional, Union, - TYPE_CHECKING -) +from typing import Any, cast, Dict, Literal, Optional, Union, TYPE_CHECKING from typing_extensions import Self from azure.core.exceptions import HttpResponseError @@ -18,29 +16,16 @@ from ._deserialize import deserialize_permission, deserialize_share_properties from ._directory_client import ShareDirectoryClient from ._file_client import ShareFileClient -from ._generated import AzureFileStorage -from ._generated.models import ( - DeleteSnapshotsOptionType, - ShareStats, - SignedIdentifier -) +from ._generated import FileClient as AzureFileStorage +from ._generated.models import DeleteSnapshotsOptionType, ShareStats, SignedIdentifier, SignedIdentifiers from ._lease import ShareLeaseClient from ._models import ShareProtocols -from ._parser import _parse_snapshot +from ._parser import _parse_snapshot, _strip_snapshot_from_url from ._serialize import get_access_conditions, get_api_version -from ._share_client_helpers import ( - _create_permission_for_share_options, - _format_url, - _from_share_url, - _parse_url -) +from ._share_client_helpers import _create_permission_for_share_options, _format_url, _from_share_url, _parse_url from ._shared.base_client import parse_connection_str, parse_query, StorageAccountHostsMixin, TransportWrapper from ._shared.request_handlers import add_metadata_headers, serialize_iso -from ._shared.response_handlers import ( - process_storage_error, - return_headers_and_deserialized, - return_response_headers -) +from ._shared.response_handlers import process_storage_error, return_headers_and_deserialized, return_response_headers if TYPE_CHECKING: @@ -101,39 +86,40 @@ class ShareClient(StorageAccountHostsMixin): # pylint: disable=too-many-public- The hostname of the secondary endpoint. :keyword int max_range_size: The maximum range size used for a file upload. Defaults to 4*1024*1024. """ + def __init__( - self, account_url: str, + self, + account_url: str, share_name: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long *, - token_intent: Optional[Literal['backup']] = None, + token_intent: Optional[Literal["backup"]] = None, **kwargs: Any ) -> None: - if hasattr(credential, 'get_token') and not token_intent: + if hasattr(credential, "get_token") and not token_intent: raise ValueError("'token_intent' keyword is required when 'credential' is an TokenCredential.") parsed_url = _parse_url(account_url, share_name) path_snapshot, sas_token = parse_query(parsed_url.query) if not sas_token and not credential: raise ValueError( - 'You need to provide either an account shared key or SAS token when creating a storage service.') + "You need to provide either an account shared key or SAS token when creating a storage service." + ) self.snapshot = _parse_snapshot(snapshot, path_snapshot) self.share_name = share_name self._query_str, credential = self._format_query_string( - sas_token=sas_token, credential=credential, share_snapshot=self.snapshot) - super(ShareClient, self).__init__( - parsed_url=parsed_url, service='file-share', credential=credential, **kwargs) - self.allow_trailing_dot = kwargs.pop('allow_trailing_dot', None) - self.allow_source_trailing_dot = kwargs.pop('allow_source_trailing_dot', None) + sas_token=sas_token, credential=credential, share_snapshot=self.snapshot + ) + super(ShareClient, self).__init__(parsed_url=parsed_url, service="file-share", credential=credential, **kwargs) + self.allow_trailing_dot = kwargs.pop("allow_trailing_dot", None) + self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( + url=_strip_snapshot_from_url(self.url), version=get_api_version(kwargs), - url=self.url, - base_url=self.url, pipeline=self._pipeline, - allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, - file_request_intent=self.file_request_intent ) def __enter__(self) -> Self: @@ -154,9 +140,12 @@ def close(self) -> None: @classmethod def from_share_url( - cls, share_url: str, + cls, + share_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long **kwargs: Any ) -> Self: """ @@ -197,10 +186,13 @@ def _format_url(self, hostname: str) -> str: @classmethod def from_connection_string( - cls, conn_str: str, + cls, + conn_str: str, share_name: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long **kwargs: Any ) -> Self: """Create ShareClient from a Connection String. @@ -238,11 +230,10 @@ def from_connection_string( :dedent: 8 :caption: Gets the share client from connection string. """ - account_url, secondary, credential = parse_connection_str(conn_str, credential, 'file') - if 'secondary_hostname' not in kwargs: - kwargs['secondary_hostname'] = secondary - return cls( - account_url, share_name=share_name, snapshot=snapshot, credential=credential, **kwargs) + account_url, secondary, credential = parse_connection_str(conn_str, credential, "file") + if "secondary_hostname" not in kwargs: + kwargs["secondary_hostname"] = secondary + return cls(account_url, share_name=share_name, snapshot=snapshot, credential=credential, **kwargs) def get_directory_client(self, directory_path: Optional[str] = None) -> ShareDirectoryClient: """Get a client to interact with the specified directory. @@ -255,15 +246,24 @@ def get_directory_client(self, directory_path: Optional[str] = None) -> ShareDir """ _pipeline = Pipeline( transport=TransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # pylint: disable=protected-access ) return ShareDirectoryClient( - self.url, share_name=self.share_name, directory_path=directory_path or "", snapshot=self.snapshot, - credential=self.credential, token_intent=self.file_request_intent, api_version=self.api_version, - _hosts=self._hosts, _configuration=self._config, _pipeline=_pipeline, - _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot) + self.url, + share_name=self.share_name, + directory_path=directory_path or "", + snapshot=self.snapshot, + credential=self.credential, + token_intent=self.file_request_intent, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + ) def get_file_client(self, file_path: str) -> ShareFileClient: """Get a client to interact with the specified file. @@ -276,15 +276,24 @@ def get_file_client(self, file_path: str) -> ShareFileClient: """ _pipeline = Pipeline( transport=TransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # pylint: disable=protected-access ) return ShareFileClient( - self.url, share_name=self.share_name, file_path=file_path, snapshot=self.snapshot, - credential=self.credential, token_intent=self.file_request_intent, api_version=self.api_version, - _hosts=self._hosts, _configuration=self._config, - _pipeline=_pipeline, _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot) + self.url, + share_name=self.share_name, + file_path=file_path, + snapshot=self.snapshot, + credential=self.credential, + token_intent=self.file_request_intent, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + ) @distributed_trace def acquire_lease(self, **kwargs: Any) -> ShareLeaseClient: @@ -322,8 +331,8 @@ def acquire_lease(self, **kwargs: Any) -> ShareLeaseClient: :dedent: 8 :caption: Acquiring a lease on a share. """ - kwargs['lease_duration'] = kwargs.pop('lease_duration', -1) - lease_id = kwargs.pop('lease_id', None) + kwargs["lease_duration"] = kwargs.pop("lease_duration", -1) + lease_id = kwargs.pop("lease_id", None) lease = ShareLeaseClient(self, lease_id=lease_id) lease.acquire(**kwargs) return lease @@ -375,38 +384,43 @@ def create_share(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 8 :caption: Creates a file share. """ - metadata = kwargs.pop('metadata', None) - quota = kwargs.pop('quota', None) - access_tier = kwargs.pop('access_tier', None) - timeout = kwargs.pop('timeout', None) - root_squash = kwargs.pop('root_squash', None) - protocols = kwargs.pop('protocols', None) - paid_bursting_bandwidth_mibps = kwargs.pop('paid_bursting_bandwidth_mibps', None) - paid_bursting_iops = kwargs.pop('paid_bursting_iops', None) - share_provisioned_iops = kwargs.pop('provisioned_iops', None) - share_provisioned_bandwidth_mibps = kwargs.pop('provisioned_bandwidth_mibps', None) - if protocols and protocols not in ['NFS', 'SMB', ShareProtocols.SMB, ShareProtocols.NFS]: + metadata = kwargs.pop("metadata", None) + quota = kwargs.pop("quota", None) + access_tier = kwargs.pop("access_tier", None) + timeout = kwargs.pop("timeout", None) + root_squash = kwargs.pop("root_squash", None) + protocols = kwargs.pop("protocols", None) + paid_bursting_bandwidth_mibps = kwargs.pop("paid_bursting_bandwidth_mibps", None) + paid_bursting_iops = kwargs.pop("paid_bursting_iops", None) + share_provisioned_iops = kwargs.pop("provisioned_iops", None) + share_provisioned_bandwidth_mibps = kwargs.pop("provisioned_bandwidth_mibps", None) + if protocols and protocols not in ["NFS", "SMB", ShareProtocols.SMB, ShareProtocols.NFS]: raise ValueError("The enabled protocol must be set to either SMB or NFS.") - if root_squash and protocols not in ['NFS', ShareProtocols.NFS]: + if root_squash and protocols not in ["NFS", ShareProtocols.NFS]: raise ValueError("The 'root_squash' keyword can only be used on NFS enabled shares.") - headers = kwargs.pop('headers', {}) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], self._client.share.create( - timeout=timeout, - metadata=metadata, - quota=quota, - access_tier=access_tier, - root_squash=root_squash, - enabled_protocols=protocols, - paid_bursting_max_bandwidth_mibps=paid_bursting_bandwidth_mibps, - paid_bursting_max_iops=paid_bursting_iops, - share_provisioned_iops=share_provisioned_iops, - share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, - cls=return_response_headers, - headers=headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.share.create( + timeout=timeout, + metadata=metadata, + quota=quota, + access_tier=access_tier, + root_squash=root_squash, + enabled_protocols=protocols, + paid_bursting_max_bandwidth_mibps=paid_bursting_bandwidth_mibps, + paid_bursting_max_iops=paid_bursting_iops, + share_provisioned_iops=share_provisioned_iops, + share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, + cls=return_response_headers, + headers=headers, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -443,23 +457,27 @@ def create_snapshot(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 12 :caption: Creates a snapshot of the file share. """ - metadata = kwargs.pop('metadata', None) - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + metadata = kwargs.pop("metadata", None) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], self._client.share.create_snapshot( - timeout=timeout, - cls=return_response_headers, - headers=headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.share.create_snapshot( + timeout=timeout, + cls=return_response_headers, + headers=headers, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace def delete_share( - self, delete_snapshots: Optional[Union[bool, Literal['include', 'include-leased']]] = False, - **kwargs: Any + self, delete_snapshots: Optional[Union[bool, Literal["include", "include-leased"]]] = False, **kwargs: Any ) -> None: """Marks the specified share for deletion. The share is later deleted during garbage collection. @@ -494,23 +512,25 @@ def delete_share( :dedent: 12 :caption: Deletes the share and any snapshots. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) delete_include = None if isinstance(delete_snapshots, bool) and delete_snapshots: delete_include = DeleteSnapshotsOptionType.INCLUDE else: - if delete_snapshots == 'include': + if delete_snapshots == "include": delete_include = DeleteSnapshotsOptionType.INCLUDE - elif delete_snapshots == 'include-leased': + elif delete_snapshots == "include-leased": delete_include = DeleteSnapshotsOptionType.INCLUDE_LEASED try: self._client.share.delete( timeout=timeout, sharesnapshot=self.snapshot, - lease_access_conditions=access_conditions, + lease_id=access_conditions, delete_snapshots=delete_include, - **kwargs) + file_request_intent=self.file_request_intent, + **kwargs + ) except HttpResponseError as error: process_storage_error(error) @@ -546,15 +566,20 @@ def get_share_properties(self, **kwargs: Any) -> "ShareProperties": :dedent: 12 :caption: Gets the share properties. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - props = cast("ShareProperties", self._client.share.get_properties( - timeout=timeout, - sharesnapshot=self.snapshot, - cls=deserialize_share_properties, - lease_access_conditions=access_conditions, - **kwargs)) + props = cast( + "ShareProperties", + self._client.share.get_properties( + timeout=timeout, + sharesnapshot=self.snapshot, + cls=deserialize_share_properties, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) props.name = self.share_name @@ -594,16 +619,21 @@ def set_share_quota(self, quota: int, **kwargs: Any) -> Dict[str, Any]: :dedent: 12 :caption: Sets the share quota. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - return cast(Dict[str, Any], self._client.share.set_properties( - timeout=timeout, - quota=quota, - access_tier=None, - lease_access_conditions=access_conditions, - cls=return_response_headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.share.set_properties( + timeout=timeout, + quota=quota, + access_tier=None, + lease_id=access_conditions, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -650,30 +680,35 @@ def set_share_properties(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 12 :caption: Sets the share properties. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) - access_tier = kwargs.pop('access_tier', None) - quota = kwargs.pop('quota', None) - root_squash = kwargs.pop('root_squash', None) - paid_bursting_bandwidth_mibps = kwargs.pop('paid_bursting_bandwidth_mibps', None) - paid_bursting_iops = kwargs.pop('paid_bursting_iops', None) - share_provisioned_iops = kwargs.pop('provisioned_iops', None) - share_provisioned_bandwidth_mibps = kwargs.pop('provisioned_bandwidth_mibps', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) + access_tier = kwargs.pop("access_tier", None) + quota = kwargs.pop("quota", None) + root_squash = kwargs.pop("root_squash", None) + paid_bursting_bandwidth_mibps = kwargs.pop("paid_bursting_bandwidth_mibps", None) + paid_bursting_iops = kwargs.pop("paid_bursting_iops", None) + share_provisioned_iops = kwargs.pop("provisioned_iops", None) + share_provisioned_bandwidth_mibps = kwargs.pop("provisioned_bandwidth_mibps", None) if all(parameter is None for parameter in [access_tier, quota, root_squash]): raise ValueError("set_share_properties should be called with at least one parameter.") try: - return cast(Dict[str, Any], self._client.share.set_properties( - timeout=timeout, - quota=quota, - access_tier=access_tier, - root_squash=root_squash, - lease_access_conditions=access_conditions, - paid_bursting_max_bandwidth_mibps=paid_bursting_bandwidth_mibps, - paid_bursting_max_iops=paid_bursting_iops, - share_provisioned_iops=share_provisioned_iops, - share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, - cls=return_response_headers, - **kwargs)) + return cast( + Dict[str, Any], + self._client.share.set_properties( + timeout=timeout, + quota=quota, + access_tier=access_tier, + root_squash=root_squash, + lease_id=access_conditions, + paid_bursting_max_bandwidth_mibps=paid_bursting_bandwidth_mibps, + paid_bursting_max_iops=paid_bursting_iops, + share_provisioned_iops=share_provisioned_iops, + share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -714,17 +749,22 @@ def set_share_metadata(self, metadata: Dict[str, str], **kwargs: Any) -> Dict[st :dedent: 12 :caption: Sets the share metadata. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], self._client.share.set_metadata( - timeout=timeout, - cls=return_response_headers, - headers=headers, - lease_access_conditions=access_conditions, - **kwargs)) + return cast( + Dict[str, Any], + self._client.share.set_metadata( + timeout=timeout, + cls=return_response_headers, + headers=headers, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -750,19 +790,24 @@ def get_share_access_policy(self, **kwargs: Any) -> Dict[str, Any]: :returns: Access policy information in a dict. :rtype: dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: response, identifiers = self._client.share.get_access_policy( timeout=timeout, cls=return_headers_and_deserialized, - lease_access_conditions=access_conditions, - **kwargs) + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ) except HttpResponseError as error: process_storage_error(error) return { - 'public_access': response.get('share_public_access'), - 'signed_identifiers': identifiers or [] + "public_access": response.get("share_public_access"), + "signed_identifiers": ( + identifiers.items_property if hasattr(identifiers, "items_property") else identifiers + ) + or [], } @distributed_trace @@ -793,12 +838,13 @@ def set_share_access_policy(self, signed_identifiers: Dict[str, "AccessPolicy"], :returns: Share-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) if len(signed_identifiers) > 5: raise ValueError( - 'Too many access policies provided. The server does not support setting ' - 'more than 5 access policies on a single resource.') + "Too many access policies provided. The server does not support setting " + "more than 5 access policies on a single resource." + ) identifiers = [] for key, value in signed_identifiers.items(): if value: @@ -806,12 +852,17 @@ def set_share_access_policy(self, signed_identifiers: Dict[str, "AccessPolicy"], value.expiry = serialize_iso(value.expiry) identifiers.append(SignedIdentifier(id=key, access_policy=value)) try: - return cast(Dict[str, Any], self._client.share.set_access_policy( - share_acl=identifiers or None, - timeout=timeout, - cls=return_response_headers, - lease_access_conditions=access_conditions, - **kwargs)) + return cast( + Dict[str, Any], + self._client.share.set_access_policy( + share_acl=SignedIdentifiers(items_property=identifiers) if identifiers else None, + timeout=timeout, + cls=return_response_headers, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -839,20 +890,23 @@ def get_share_stats(self, **kwargs: Any) -> int: :return: The approximate size of the data (in bytes) stored on the share. :rtype: int """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - stats = cast(ShareStats, self._client.share.get_statistics( - timeout=timeout, - lease_access_conditions=access_conditions, - **kwargs)) + stats = cast( + ShareStats, + self._client.share.get_statistics( + timeout=timeout, lease_id=access_conditions, file_request_intent=self.file_request_intent, **kwargs + ), + ) return stats.share_usage_bytes except HttpResponseError as error: process_storage_error(error) @distributed_trace def list_directories_and_files( - self, directory_name: Optional[str] = None, + self, + directory_name: Optional[str] = None, name_starts_with: Optional[str] = None, marker: Optional[str] = None, **kwargs: Any @@ -901,11 +955,12 @@ def list_directories_and_files( :dedent: 12 :caption: List directories and files in the share. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) directory = self.get_directory_client(directory_name) - kwargs.setdefault('merge_span', True) + kwargs.setdefault("merge_span", True) return directory.list_directories_and_files( - name_starts_with=name_starts_with, marker=marker, timeout=timeout, **kwargs) + name_starts_with=name_starts_with, marker=marker, timeout=timeout, **kwargs + ) @distributed_trace def create_permission_for_share(self, file_permission: str, **kwargs: Any) -> Optional[str]: @@ -929,10 +984,13 @@ def create_permission_for_share(self, file_permission: str, **kwargs: Any) -> Op :returns: A file permission key :rtype: str or None """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) options = _create_permission_for_share_options(file_permission, timeout=timeout, **kwargs) try: - return cast(Optional[str], self._client.share.create_permission(**options)) + return cast( + Optional[str], + self._client.share.create_permission(file_request_intent=self.file_request_intent, **options), + ) except HttpResponseError as error: process_storage_error(error) @@ -956,13 +1014,18 @@ def get_permission_for_share(self, permission_key: str, **kwargs: Any) -> str: :returns: A file permission (a portable SDDL) :rtype: str """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) try: - return cast(str, self._client.share.get_permission( - file_permission_key=permission_key, - cls=deserialize_permission, - timeout=timeout, - **kwargs)) + return cast( + str, + self._client.share.get_permission( + file_permission_key=permission_key, + cls=deserialize_permission, + timeout=timeout, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1002,7 +1065,7 @@ def create_directory(self, directory_name: str, **kwargs: Any) -> ShareDirectory :rtype: ~azure.storage.fileshare.ShareDirectoryClient """ directory = self.get_directory_client(directory_name) - kwargs.setdefault('merge_span', True) + kwargs.setdefault("merge_span", True) directory.create_directory(**kwargs) return directory diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client_helpers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client_helpers.py index 7d3f041db0cf..11e16d5832b5 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client_helpers.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client_helpers.py @@ -4,10 +4,7 @@ # license information. # -------------------------------------------------------------------------- -from typing import ( - Any, Dict, Optional, Tuple, Union, - TYPE_CHECKING -) +from typing import Any, Dict, Optional, Tuple, Union, TYPE_CHECKING from urllib.parse import quote, unquote, urlparse from ._deserialize import deserialize_permission_key @@ -21,11 +18,11 @@ def _parse_url(account_url: str, share_name: str) -> "ParseResult": try: - if not account_url.lower().startswith('http'): + if not account_url.lower().startswith("http"): account_url = "https://" + account_url except AttributeError as exc: raise ValueError("Account URL must be a string.") from exc - parsed_url = urlparse(account_url.rstrip('/')) + parsed_url = urlparse(account_url.rstrip("/")) if not share_name: raise ValueError("Please specify a share name.") if not parsed_url.netloc: @@ -35,21 +32,21 @@ def _parse_url(account_url: str, share_name: str) -> "ParseResult": def _format_url(scheme: str, hostname: str, share_name: Union[str, bytes], query_str: str) -> str: if isinstance(share_name, str): - share_name = share_name.encode('UTF-8') + share_name = share_name.encode("UTF-8") return f"{scheme}://{hostname}/{quote(share_name)}{query_str}" def _from_share_url(share_url: str, snapshot: Optional[Union[str, Dict[str, Any]]]) -> Tuple[str, str, Optional[str]]: try: - if not share_url.lower().startswith('http'): + if not share_url.lower().startswith("http"): share_url = "https://" + share_url except AttributeError as exc: raise ValueError("Share URL must be a string.") from exc - parsed_url = urlparse(share_url.rstrip('/')) + parsed_url = urlparse(share_url.rstrip("/")) if not (parsed_url.path and parsed_url.netloc): raise ValueError(f"Invalid URL: {share_url}") - share_path = parsed_url.path.lstrip('/').split('/') + share_path = parsed_url.path.lstrip("/").split("/") account_path = "" if len(share_path) > 1: account_path = "/" + "/".join(share_path[:-1]) @@ -67,9 +64,9 @@ def _from_share_url(share_url: str, snapshot: Optional[Union[str, Dict[str, Any] def _create_permission_for_share_options(file_permission: str, **kwargs: Any) -> Dict[str, Any]: options = { - 'share_permission': SharePermission(permission=file_permission), - 'cls': deserialize_permission_key, - 'timeout': kwargs.pop('timeout', None), + "permission": SharePermission(permission=file_permission), + "cls": deserialize_permission_key, + "timeout": kwargs.pop("timeout", None), } options.update(kwargs) return options diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_service_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_service_client.py index 8c35e2ee3d3b..f44ec757cdc7 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_service_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_service_client.py @@ -7,17 +7,14 @@ import sys import functools -from typing import ( - Union, Optional, Any, Dict, List, - TYPE_CHECKING -) +from typing import Union, Optional, Any, Dict, List, TYPE_CHECKING from typing_extensions import Self from azure.core.exceptions import HttpResponseError from azure.core.paging import ItemPaged from azure.core.pipeline import Pipeline from azure.core.tracing.decorator import distributed_trace -from ._generated import AzureFileStorage +from ._generated import FileClient as AzureFileStorage from ._generated.models import KeyInfo, StorageServiceProperties from ._models import ( CorsRule, @@ -25,6 +22,7 @@ SharePropertiesPaged, service_properties_deserialize, ) +from ._parser import _strip_snapshot_from_url from ._serialize import get_api_version from ._share_client import ShareClient from ._share_service_client_helpers import _parse_url @@ -103,35 +101,35 @@ class ShareServiceClient(StorageAccountHostsMixin): :dedent: 8 :caption: Create the share service client with url and credential. """ + def __init__( - self, account_url: str, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long + self, + account_url: str, + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long *, - token_intent: Optional[Literal['backup']] = None, - **kwargs: Any + token_intent: Optional[Literal["backup"]] = None, + **kwargs: Any, ) -> None: - if hasattr(credential, 'get_token') and not token_intent: + if hasattr(credential, "get_token") and not token_intent: raise ValueError("'token_intent' keyword is required when 'credential' is an TokenCredential.") parsed_url = _parse_url(account_url=account_url) _, sas_token = parse_query(parsed_url.query) if not sas_token and not credential: raise ValueError( - 'You need to provide either an account shared key or SAS token when creating a storage service.') + "You need to provide either an account shared key or SAS token when creating a storage service." + ) self._query_str, credential = self._format_query_string(sas_token, credential) - super(ShareServiceClient, self).__init__( - parsed_url, service='file-share', credential=credential, **kwargs) - self.allow_trailing_dot = kwargs.pop('allow_trailing_dot', None) - self.allow_source_trailing_dot = kwargs.pop('allow_source_trailing_dot', None) + super(ShareServiceClient, self).__init__(parsed_url, service="file-share", credential=credential, **kwargs) + self.allow_trailing_dot = kwargs.pop("allow_trailing_dot", None) + self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( + url=_strip_snapshot_from_url(self.url), version=get_api_version(kwargs), - url=self.url, - base_url=self.url, pipeline=self._pipeline, - allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, - file_request_intent=self.file_request_intent ) def __enter__(self) -> Self: @@ -162,9 +160,12 @@ def _format_url(self, hostname: str) -> str: @classmethod def from_connection_string( - cls, conn_str: str, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + cls, + conn_str: str, + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "TokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """Create ShareServiceClient from a Connection String. @@ -196,9 +197,9 @@ def from_connection_string( :dedent: 8 :caption: Create the share service client with connection string. """ - account_url, secondary, credential = parse_connection_str(conn_str, credential, 'file') - if 'secondary_hostname' not in kwargs: - kwargs['secondary_hostname'] = secondary + account_url, secondary, credential = parse_connection_str(conn_str, credential, "file") + if "secondary_hostname" not in kwargs: + kwargs["secondary_hostname"] = secondary return cls(account_url, credential=credential, **kwargs) @distributed_trace @@ -209,7 +210,7 @@ def get_user_delegation_key( start: Optional["datetime"] = None, delegated_user_tid: Optional[str] = None, timeout: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> "UserDelegationKey": """ Obtain a user delegation key for the purpose of signing SAS tokens. @@ -233,15 +234,11 @@ def get_user_delegation_key( :rtype: ~azure.storage.fileshare.UserDelegationKey """ key_info = KeyInfo( - start=_to_utc_datetime(start), - expiry=_to_utc_datetime(expiry), - delegated_user_tid=delegated_user_tid + start=_to_utc_datetime(start), expiry=_to_utc_datetime(expiry), delegated_user_tid=delegated_user_tid ) try: user_delegation_key = self._client.service.get_user_delegation_key( # type: ignore - key_info=key_info, - timeout=timeout, - **kwargs + key_info=key_info, timeout=timeout, **kwargs ) except HttpResponseError as error: process_storage_error(error) @@ -271,20 +268,23 @@ def get_service_properties(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 8 :caption: Get file share service properties. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) try: - service_props = self._client.service.get_properties(timeout=timeout, **kwargs) + service_props = self._client.service.get_properties( + timeout=timeout, file_request_intent=self.file_request_intent, **kwargs + ) return service_properties_deserialize(service_props) except HttpResponseError as error: process_storage_error(error) @distributed_trace def set_service_properties( - self, hour_metrics: Optional["Metrics"] = None, + self, + hour_metrics: Optional["Metrics"] = None, minute_metrics: Optional["Metrics"] = None, cors: Optional[List[CorsRule]] = None, protocol: Optional["ShareProtocolSettings"] = None, - **kwargs: Any + **kwargs: Any, ) -> None: """Sets the properties of a storage account's File Share service, including Azure Storage Analytics. If an element (e.g. hour_metrics) is left as None, the @@ -323,24 +323,30 @@ def set_service_properties( :dedent: 8 :caption: Sets file share service properties. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) props = StorageServiceProperties( hour_metrics=hour_metrics, minute_metrics=minute_metrics, cors=CorsRule._to_generated(cors), # pylint: disable=protected-access - protocol=protocol + protocol=protocol, ) try: - self._client.service.set_properties(storage_service_properties=props, timeout=timeout, **kwargs) + self._client.service.set_properties( + storage_service_properties=props, + timeout=timeout, + file_request_intent=self.file_request_intent, + **kwargs, + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace def list_shares( - self, name_starts_with: Optional[str] = None, + self, + name_starts_with: Optional[str] = None, include_metadata: Optional[bool] = False, include_snapshots: Optional[bool] = False, - **kwargs: Any + **kwargs: Any, ) -> ItemPaged[ShareProperties]: """Returns auto-paging iterable of dict-like ShareProperties under the specified account. The generator will lazily follow the continuation tokens returned by @@ -374,25 +380,30 @@ def list_shares( :dedent: 12 :caption: List shares in the file share service. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) include = [] - include_deleted = kwargs.pop('include_deleted', None) + include_deleted = kwargs.pop("include_deleted", None) if include_deleted: include.append("deleted") if include_metadata: - include.append('metadata') + include.append("metadata") if include_snapshots: - include.append('snapshots') + include.append("snapshots") - results_per_page = kwargs.pop('results_per_page', None) + results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( self._client.service.list_shares_segment, include=include, timeout=timeout, - **kwargs) + file_request_intent=self.file_request_intent, + **kwargs, + ) return ItemPaged( - command, prefix=name_starts_with, results_per_page=results_per_page, - page_iterator_class=SharePropertiesPaged) + command, + prefix=name_starts_with, + results_per_page=results_per_page, + page_iterator_class=SharePropertiesPaged, + ) @distributed_trace def create_share(self, share_name: str, **kwargs: Any) -> ShareClient: @@ -426,28 +437,26 @@ def create_share(self, share_name: str, **kwargs: Any) -> ShareClient: :dedent: 8 :caption: Create a share in the file share service. """ - metadata = kwargs.pop('metadata', None) - quota = kwargs.pop('quota', None) - timeout = kwargs.pop('timeout', None) - provisioned_iops = kwargs.pop('provisioned_iops', None) - provisioned_bandwidth_mibps = kwargs.pop('provisioned_bandwidth_mibps', None) + metadata = kwargs.pop("metadata", None) + quota = kwargs.pop("quota", None) + timeout = kwargs.pop("timeout", None) + provisioned_iops = kwargs.pop("provisioned_iops", None) + provisioned_bandwidth_mibps = kwargs.pop("provisioned_bandwidth_mibps", None) share = self.get_share_client(share_name) - kwargs.setdefault('merge_span', True) + kwargs.setdefault("merge_span", True) share.create_share( metadata=metadata, quota=quota, timeout=timeout, provisioned_iops=provisioned_iops, provisioned_bandwidth_mibps=provisioned_bandwidth_mibps, - **kwargs + **kwargs, ) return share @distributed_trace def delete_share( - self, share_name: Union[ShareProperties, str], - delete_snapshots: Optional[bool] = False, - **kwargs: Any + self, share_name: Union[ShareProperties, str], delete_snapshots: Optional[bool] = False, **kwargs: Any ) -> None: """Marks the specified share for deletion. The share is later deleted during garbage collection. @@ -475,11 +484,10 @@ def delete_share( :dedent: 12 :caption: Delete a share in the file share service. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) share = self.get_share_client(share_name) - kwargs.setdefault('merge_span', True) - share.delete_share( - delete_snapshots=delete_snapshots, timeout=timeout, **kwargs) + kwargs.setdefault("merge_span", True) + share.delete_share(delete_snapshots=delete_snapshots, timeout=timeout, **kwargs) @distributed_trace def undelete_share(self, deleted_share_name: str, deleted_share_version: str, **kwargs: Any) -> ShareClient: @@ -508,16 +516,18 @@ def undelete_share(self, deleted_share_name: str, deleted_share_version: str, ** share = self.get_share_client(deleted_share_name) try: - share._client.share.restore(deleted_share_name=deleted_share_name, # pylint: disable=protected-access - deleted_share_version=deleted_share_version, - timeout=kwargs.pop('timeout', None), **kwargs) + share._client.share.restore( # pylint: disable=protected-access + deleted_share_name=deleted_share_name, + deleted_share_version=deleted_share_version, + timeout=kwargs.pop("timeout", None), + **kwargs, + ) return share except HttpResponseError as error: process_storage_error(error) def get_share_client( - self, share: Union[ShareProperties, str], - snapshot: Optional[Union[Dict[str, Any], str]] = None + self, share: Union[ShareProperties, str], snapshot: Optional[Union[Dict[str, Any], str]] = None ) -> ShareClient: """Get a client to interact with the specified share. The share need not already exist. @@ -547,12 +557,20 @@ def get_share_client( share_name = share _pipeline = Pipeline( - transport=TransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # pylint: disable=protected-access + transport=TransportWrapper(self._pipeline._transport), # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # pylint: disable=protected-access ) return ShareClient( - self.url, share_name=share_name, snapshot=snapshot, credential=self.credential, - api_version=self.api_version, _hosts=self._hosts, - _configuration=self._config, _pipeline=_pipeline, _location_mode=self._location_mode, - allow_trailing_dot=self.allow_trailing_dot, allow_source_trailing_dot=self.allow_source_trailing_dot, - token_intent=self.file_request_intent) + self.url, + share_name=share_name, + snapshot=snapshot, + credential=self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, + ) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_service_client_helpers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_service_client_helpers.py index 9a6ebe8e7c4a..cfc1d7f4ca2d 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_service_client_helpers.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_service_client_helpers.py @@ -17,7 +17,7 @@ def _parse_url(account_url: str) -> "ParseResult": account_url = "https://" + account_url except AttributeError as exc: raise ValueError("Account URL must be a string.") from exc - parsed_url = urlparse(account_url.rstrip('/')) + parsed_url = urlparse(account_url.rstrip("/")) if not parsed_url.netloc: raise ValueError(f"Invalid URL: {account_url}") return parsed_url diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/base_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/base_client.py index 57095ca402aa..08e54267f1c7 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/base_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/base_client.py @@ -86,7 +86,7 @@ def _construct_endpoints(netloc: str, account_part: str) -> Tuple[str, str, str] :return: The account name, primary hostname, and secondary hostname. :rtype: Tuple[str, str, str] """ - domain_suffix = netloc[len(account_part):] + domain_suffix = netloc[len(account_part) :] secondary_idx = account_part.find(_SECONDARY_SUFFIX) # Case where customer provides secondary URL @@ -184,7 +184,7 @@ def url(self) -> str: :return: The full endpoint URL to this entity, including SAS token if used. :rtype: str """ - return self._format_url(self._hosts[self._location_mode]) # type: ignore + return self._format_url(self._hosts[self._location_mode]) # type: ignore @property def primary_endpoint(self) -> str: @@ -217,7 +217,7 @@ def secondary_endpoint(self) -> str: """ if not self._hosts[LocationMode.SECONDARY]: raise ValueError("No secondary host configured.") - return self._format_url(self._hosts[LocationMode.SECONDARY]) # type: ignore + return self._format_url(self._hosts[LocationMode.SECONDARY]) # type: ignore @property def secondary_hostname(self) -> Optional[str]: @@ -455,7 +455,7 @@ def parse_connection_str( if any(len(tup) != 2 for tup in conn_settings_list): raise ValueError("Connection string is either blank or malformed.") conn_settings = dict((key.upper(), val) for key, val in conn_settings_list) - if conn_settings.get('USEDEVELOPMENTSTORAGE') == 'true': + if conn_settings.get("USEDEVELOPMENTSTORAGE") == "true": return _get_development_storage_endpoint(service), None, DEVSTORE_ACCOUNT_KEY endpoints = _SERVICE_PARAMS[service] primary = None diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/base_client_async.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/base_client_async.py index 16aba3116029..400f7d6f6dff 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/base_client_async.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/base_client_async.py @@ -210,7 +210,7 @@ def parse_connection_str( if any(len(tup) != 2 for tup in conn_settings_list): raise ValueError("Connection string is either blank or malformed.") conn_settings = dict((key.upper(), val) for key, val in conn_settings_list) - if conn_settings.get('USEDEVELOPMENTSTORAGE') == 'true': + if conn_settings.get("USEDEVELOPMENTSTORAGE") == "true": return _get_development_storage_endpoint(service), None, DEVSTORE_ACCOUNT_KEY endpoints = _SERVICE_PARAMS[service] primary = None diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/policies.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/policies.py index 61a4fdb15bdd..cec4acf285ab 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/policies.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/policies.py @@ -456,7 +456,7 @@ def _set_next_host_location(self, settings: Dict[str, Any], request: "PipelineRe def configure_retries(self, request: "PipelineRequest") -> Dict[str, Any]: """ Configure the retry settings for the request. - + :param request: A pipeline request object. :type request: ~azure.core.pipeline.PipelineRequest :return: A dictionary containing the retry settings. @@ -496,7 +496,7 @@ def get_backoff_time(self, settings: Dict[str, Any]) -> float: # pylint: disabl def sleep(self, settings, transport): """Sleep for the backoff time. - + :param Dict[str, Any] settings: The configurable values pertaining to the sleep operation. :param transport: The transport to use for sleeping. :type transport: @@ -570,7 +570,7 @@ def increment( def send(self, request): """Send the request with retry logic. - + :param request: A pipeline request object. :type request: ~azure.core.pipeline.PipelineRequest :return: A pipeline response object. @@ -731,11 +731,11 @@ def __init__(self, credential: "TokenCredential", audience: str, **kwargs: Any) def on_challenge(self, request: "PipelineRequest", response: "PipelineResponse") -> bool: """Handle the challenge from the service and authorize the request. - + :param request: The request object. :type request: ~azure.core.pipeline.PipelineRequest :param response: The response object. - :type response: ~azure.core.pipeline.PipelineResponse + :type response: ~azure.core.pipeline.PipelineResponse :return: True if the request was authorized, False otherwise. :rtype: bool """ diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/request_handlers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/request_handlers.py index b23f65859690..8bef3c487b30 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/request_handlers.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/request_handlers.py @@ -118,11 +118,11 @@ def validate_and_format_range_headers( if align_to_page: if start_range is not None and start_range % 512 != 0: raise ValueError( - f"Invalid page blob start_range: {start_range}. " "The size must be aligned to a 512-byte boundary." + f"Invalid page blob start_range: {start_range}. The size must be aligned to a 512-byte boundary." ) if end_range is not None and end_range % 512 != 511: raise ValueError( - f"Invalid page blob end_range: {end_range}. " "The size must be aligned to a 512-byte boundary." + f"Invalid page blob end_range: {end_range}. The size must be aligned to a 512-byte boundary." ) # Format based on whether end_range is present diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/response_handlers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/response_handlers.py index 1ed0d1073331..19f9d1086c66 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/response_handlers.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/response_handlers.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -176,8 +177,11 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p error_message += f"\n{name}:{info}" if additional_data.get("headername") == "x-ms-version" and error_code == StorageErrorCode.INVALID_HEADER_VALUE: - error_message = ("The provided service version is not enabled on this storage account." + - f"Please see {SV_DOCS_URL} for additional information.\n" + error_message) + error_message = ( + "The provided service version is not enabled on this storage account." + + f"Please see {SV_DOCS_URL} for additional information.\n" + + error_message + ) # No need to create an instance if it has already been serialized by the generated layer if serialized: @@ -206,8 +210,16 @@ def parse_to_internal_user_delegation_key(service_user_delegation_key): internal_user_delegation_key.signed_oid = service_user_delegation_key.signed_oid internal_user_delegation_key.signed_tid = service_user_delegation_key.signed_tid internal_user_delegation_key.signed_delegated_user_tid = service_user_delegation_key.signed_delegated_user_tid - internal_user_delegation_key.signed_start = _to_utc_datetime(service_user_delegation_key.signed_start) - internal_user_delegation_key.signed_expiry = _to_utc_datetime(service_user_delegation_key.signed_expiry) + internal_user_delegation_key.signed_start = ( + service_user_delegation_key.signed_start + if isinstance(service_user_delegation_key.signed_start, str) + else _to_utc_datetime(service_user_delegation_key.signed_start) + ) + internal_user_delegation_key.signed_expiry = ( + service_user_delegation_key.signed_expiry + if isinstance(service_user_delegation_key.signed_expiry, str) + else _to_utc_datetime(service_user_delegation_key.signed_expiry) + ) internal_user_delegation_key.signed_service = service_user_delegation_key.signed_service internal_user_delegation_key.signed_version = service_user_delegation_key.signed_version internal_user_delegation_key.value = service_user_delegation_key.value diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/uploads.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/uploads.py index 7a5fb3f3dc91..9c55e82257d2 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/uploads.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/uploads.py @@ -56,6 +56,10 @@ def upload_data_chunks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None + if parallel: + # Access conditions do not work with parallelism + kwargs.pop("etag", None) + kwargs.pop("match_condition", None) uploader = uploader_class( service=service, @@ -96,6 +100,10 @@ def upload_substream_blocks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None + if parallel: + # Access conditions do not work with parallelism + kwargs.pop("etag", None) + kwargs.pop("match_condition", None) uploader = uploader_class( service=service, total_size=total_size, @@ -262,9 +270,9 @@ def _upload_chunk(self, chunk_offset, chunk_data): index = f"{chunk_offset:032d}" block_id = encode_base64(url_quote(encode_base64(index))) self.service.stage_block( - block_id, - len(chunk_data), - chunk_data, + block_id=block_id, + content_length=len(chunk_data), + body=chunk_data, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -275,9 +283,9 @@ def _upload_substream_block(self, index, block_stream): try: block_id = f"BlockId{(index//self.chunk_size):05}" self.service.stage_block( - block_id, - len(block_stream), - block_stream, + block_id=block_id, + content_length=len(block_stream), + body=block_stream, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -311,8 +319,8 @@ def _upload_chunk(self, chunk_offset, chunk_data): **self.request_options, ) - if not self.parallel and self.request_options.get("modified_access_conditions"): - self.request_options["modified_access_conditions"].if_match = self.response_headers["etag"] + if not self.parallel and self.request_options.get("etag"): + self.request_options["etag"] = self.response_headers["etag"] def _upload_substream_block(self, index, block_stream): pass @@ -336,9 +344,7 @@ def _upload_chunk(self, chunk_offset, chunk_data): ) self.current_length = int(self.response_headers["blob_append_offset"]) else: - self.request_options["append_position_access_conditions"].append_position = ( - self.current_length + chunk_offset - ) + self.request_options["append_position"] = self.current_length + chunk_offset self.response_headers = self.service.append_block( body=chunk_data, content_length=len(chunk_data), diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/uploads_async.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/uploads_async.py index 6ed5ba1d0f91..c1fa2a428dcc 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/uploads_async.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/uploads_async.py @@ -73,6 +73,10 @@ async def upload_data_chunks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None + if parallel: + # Access conditions do not work with parallelism + kwargs.pop("etag", None) + kwargs.pop("match_condition", None) uploader = uploader_class( service=service, @@ -119,6 +123,10 @@ async def upload_substream_blocks( if parallel and "modified_access_conditions" in kwargs: # Access conditions do not work with parallelism kwargs["modified_access_conditions"] = None + if parallel: + # Access conditions do not work with parallelism + kwargs.pop("etag", None) + kwargs.pop("match_condition", None) uploader = uploader_class( service=service, total_size=total_size, @@ -287,8 +295,8 @@ async def _upload_chunk(self, chunk_offset, chunk_data): index = f"{chunk_offset:032d}" block_id = encode_base64(url_quote(encode_base64(index))) await self.service.stage_block( - block_id, - len(chunk_data), + block_id=block_id, + content_length=len(chunk_data), body=chunk_data, data_stream_total=self.total_size, upload_stream_current=self.progress_total, @@ -300,9 +308,9 @@ async def _upload_substream_block(self, index, block_stream): try: block_id = f"BlockId{(index//self.chunk_size):05}" await self.service.stage_block( - block_id, - len(block_stream), - block_stream, + block_id=block_id, + content_length=len(block_stream), + body=block_stream, data_stream_total=self.total_size, upload_stream_current=self.progress_total, **self.request_options, @@ -339,8 +347,8 @@ async def _upload_chunk(self, chunk_offset, chunk_data): **self.request_options, ) - if not self.parallel and self.request_options.get("modified_access_conditions"): - self.request_options["modified_access_conditions"].if_match = self.response_headers["etag"] + if not self.parallel and self.request_options.get("etag"): + self.request_options["etag"] = self.response_headers["etag"] async def _upload_substream_block(self, index, block_stream): pass @@ -364,9 +372,7 @@ async def _upload_chunk(self, chunk_offset, chunk_data): ) self.current_length = int(self.response_headers["blob_append_offset"]) else: - self.request_options["append_position_access_conditions"].append_position = ( - self.current_length + chunk_offset - ) + self.request_options["append_position"] = self.current_length + chunk_offset self.response_headers = await self.service.append_block( body=chunk_data, content_length=len(chunk_data), diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared_access_signature.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared_access_signature.py index 6880a52022a8..0a7f24fa711b 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared_access_signature.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared_access_signature.py @@ -5,10 +5,7 @@ # -------------------------------------------------------------------------- # pylint: disable=docstring-keyword-should-match-keyword-only -from typing import ( - Any, Callable, List, Optional, Union, - TYPE_CHECKING -) +from typing import Any, Callable, List, Optional, Union, TYPE_CHECKING from urllib.parse import parse_qs from ._shared import sign_string @@ -18,12 +15,7 @@ if TYPE_CHECKING: from datetime import datetime - from azure.storage.fileshare import ( - AccountSasPermissions, - FileSasPermissions, - ShareSasPermissions, - ResourceTypes - ) + from azure.storage.fileshare import AccountSasPermissions, FileSasPermissions, ShareSasPermissions, ResourceTypes class FileSharedAccessSignature(SharedAccessSignature): @@ -54,7 +46,8 @@ def __init__( self.user_delegation_key = user_delegation_key def generate_file( - self, share_name: str, + self, + share_name: str, directory_name: Optional[str] = None, file_name: Optional[str] = None, permission: Optional[Union["FileSasPermissions", str]] = None, @@ -69,7 +62,7 @@ def generate_file( content_language: Optional[str] = None, content_type: Optional[str] = None, user_delegation_oid: Optional[str] = None, - sts_hook: Optional[Callable[[str], None]] = None + sts_hook: Optional[Callable[[str], None]] = None, ) -> str: """ Generates a shared access signature for the file. @@ -145,20 +138,21 @@ def generate_file( """ resource_path = share_name if directory_name is not None: - resource_path += '/' + str(directory_name) + resource_path += "/" + str(directory_name) if file_name is not None: - resource_path += '/' + str(file_name) + resource_path += "/" + str(file_name) sas = _FileSharedAccessHelper() sas.add_base(permission, expiry, start, ip, protocol, self.x_ms_version) sas.add_id(policy_id) sas.add_user_delegation_oid(user_delegation_oid) - sas.add_resource('f') - sas.add_override_response_headers(cache_control, content_disposition, - content_encoding, content_language, - content_type) - sas.add_resource_signature(self.account_name, self.account_key, resource_path, - user_delegation_key=self.user_delegation_key) + sas.add_resource("f") + sas.add_override_response_headers( + cache_control, content_disposition, content_encoding, content_language, content_type + ) + sas.add_resource_signature( + self.account_name, self.account_key, resource_path, user_delegation_key=self.user_delegation_key + ) if sts_hook is not None: sts_hook(sas.string_to_sign) @@ -166,7 +160,8 @@ def generate_file( return sas.get_token() def generate_share( - self, share_name: str, + self, + share_name: str, permission: Optional[Union["ShareSasPermissions", str]] = None, expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, @@ -181,7 +176,7 @@ def generate_share( user_delegation_oid: Optional[str] = None, sts_hook: Optional[Callable[[str], None]] = None, ) -> str: - ''' + """ Generates a shared access signature for the share. Use the returned signature with the sas_token parameter of FileService. @@ -247,17 +242,18 @@ def generate_share( :type sts_hook: Optional[Callable[[str], None]] :returns: The generated SAS token for the account. :rtype: str - ''' + """ sas = _FileSharedAccessHelper() sas.add_base(permission, expiry, start, ip, protocol, self.x_ms_version) sas.add_id(policy_id) sas.add_user_delegation_oid(user_delegation_oid) - sas.add_resource('s') - sas.add_override_response_headers(cache_control, content_disposition, - content_encoding, content_language, - content_type) - sas.add_resource_signature(self.account_name, self.account_key, share_name, - user_delegation_key=self.user_delegation_key) + sas.add_resource("s") + sas.add_override_response_headers( + cache_control, content_disposition, content_encoding, content_language, content_type + ) + sas.add_resource_signature( + self.account_name, self.account_key, share_name, user_delegation_key=self.user_delegation_key + ) if sts_hook is not None: sts_hook(sas.string_to_sign) @@ -269,21 +265,22 @@ class _FileSharedAccessHelper(_SharedAccessHelper): def add_resource_signature(self, account_name, account_key, path, user_delegation_key=None): def get_value_to_append(query): - return_value = self.query_dict.get(query) or '' - return return_value + '\n' + return_value = self.query_dict.get(query) or "" + return return_value + "\n" - if path[0] != '/': - path = '/' + path + if path[0] != "/": + path = "/" + path - canonicalized_resource = '/file/' + account_name + path + '\n' + canonicalized_resource = "/file/" + account_name + path + "\n" # Form the string to sign from shared_access_policy and canonicalized # resource. The order of values is important. - string_to_sign = \ - (get_value_to_append(QueryStringConstants.SIGNED_PERMISSION) + - get_value_to_append(QueryStringConstants.SIGNED_START) + - get_value_to_append(QueryStringConstants.SIGNED_EXPIRY) + - canonicalized_resource) + string_to_sign = ( + get_value_to_append(QueryStringConstants.SIGNED_PERMISSION) + + get_value_to_append(QueryStringConstants.SIGNED_START) + + get_value_to_append(QueryStringConstants.SIGNED_EXPIRY) + + canonicalized_resource + ) if user_delegation_key is not None: self._add_query(QueryStringConstants.SIGNED_OID, user_delegation_key.signed_oid) @@ -293,39 +290,41 @@ def get_value_to_append(query): self._add_query(QueryStringConstants.SIGNED_KEY_SERVICE, user_delegation_key.signed_service) self._add_query(QueryStringConstants.SIGNED_KEY_VERSION, user_delegation_key.signed_version) self._add_query( - QueryStringConstants.SIGNED_KEY_DELEGATED_USER_TID, - user_delegation_key.signed_delegated_user_tid + QueryStringConstants.SIGNED_KEY_DELEGATED_USER_TID, user_delegation_key.signed_delegated_user_tid ) - string_to_sign += \ - (get_value_to_append(QueryStringConstants.SIGNED_OID) + - get_value_to_append(QueryStringConstants.SIGNED_TID) + - get_value_to_append(QueryStringConstants.SIGNED_KEY_START) + - get_value_to_append(QueryStringConstants.SIGNED_KEY_EXPIRY) + - get_value_to_append(QueryStringConstants.SIGNED_KEY_SERVICE) + - get_value_to_append(QueryStringConstants.SIGNED_KEY_VERSION) + - get_value_to_append(QueryStringConstants.SIGNED_KEY_DELEGATED_USER_TID) + - get_value_to_append(QueryStringConstants.SIGNED_DELEGATED_USER_OID)) + string_to_sign += ( + get_value_to_append(QueryStringConstants.SIGNED_OID) + + get_value_to_append(QueryStringConstants.SIGNED_TID) + + get_value_to_append(QueryStringConstants.SIGNED_KEY_START) + + get_value_to_append(QueryStringConstants.SIGNED_KEY_EXPIRY) + + get_value_to_append(QueryStringConstants.SIGNED_KEY_SERVICE) + + get_value_to_append(QueryStringConstants.SIGNED_KEY_VERSION) + + get_value_to_append(QueryStringConstants.SIGNED_KEY_DELEGATED_USER_TID) + + get_value_to_append(QueryStringConstants.SIGNED_DELEGATED_USER_OID) + ) else: string_to_sign += get_value_to_append(QueryStringConstants.SIGNED_IDENTIFIER) - string_to_sign += \ - (get_value_to_append(QueryStringConstants.SIGNED_IP) + - get_value_to_append(QueryStringConstants.SIGNED_PROTOCOL) + - get_value_to_append(QueryStringConstants.SIGNED_VERSION) + - get_value_to_append(QueryStringConstants.SIGNED_CACHE_CONTROL) + - get_value_to_append(QueryStringConstants.SIGNED_CONTENT_DISPOSITION) + - get_value_to_append(QueryStringConstants.SIGNED_CONTENT_ENCODING) + - get_value_to_append(QueryStringConstants.SIGNED_CONTENT_LANGUAGE) + - get_value_to_append(QueryStringConstants.SIGNED_CONTENT_TYPE)) + string_to_sign += ( + get_value_to_append(QueryStringConstants.SIGNED_IP) + + get_value_to_append(QueryStringConstants.SIGNED_PROTOCOL) + + get_value_to_append(QueryStringConstants.SIGNED_VERSION) + + get_value_to_append(QueryStringConstants.SIGNED_CACHE_CONTROL) + + get_value_to_append(QueryStringConstants.SIGNED_CONTENT_DISPOSITION) + + get_value_to_append(QueryStringConstants.SIGNED_CONTENT_ENCODING) + + get_value_to_append(QueryStringConstants.SIGNED_CONTENT_LANGUAGE) + + get_value_to_append(QueryStringConstants.SIGNED_CONTENT_TYPE) + ) # remove the trailing newline - if string_to_sign[-1] == '\n': + if string_to_sign[-1] == "\n": string_to_sign = string_to_sign[:-1] - self._add_query(QueryStringConstants.SIGNED_SIGNATURE, - sign_string(account_key if user_delegation_key is None else user_delegation_key.value, - string_to_sign)) + self._add_query( + QueryStringConstants.SIGNED_SIGNATURE, + sign_string(account_key if user_delegation_key is None else user_delegation_key.value, string_to_sign), + ) self.string_to_sign = string_to_sign @@ -624,7 +623,7 @@ def generate_file_sas( raise ValueError("Either user_delegation_key or account_key must be provided.") sas = FileSharedAccessSignature(account_name, account_key=account_key, user_delegation_key=user_delegation_key) if len(file_path) > 1: - dir_path = '/'.join(file_path[:-1]) + dir_path = "/".join(file_path[:-1]) else: dir_path = None return sas.generate_file( diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_version.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_version.py index b9d6b67ccaeb..6f9bb76017d3 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_version.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_version.py @@ -1,7 +1,9 @@ -# ------------------------------------------------------------------------- +# coding=utf-8 +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- VERSION = "12.27.0b1" diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/__init__.py index 73393b819df4..489635c591d1 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/__init__.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/__init__.py @@ -12,9 +12,9 @@ __all__ = [ - 'ShareFileClient', - 'ShareDirectoryClient', - 'ShareClient', - 'ShareServiceClient', - 'ShareLeaseClient', + "ShareFileClient", + "ShareDirectoryClient", + "ShareClient", + "ShareServiceClient", + "ShareLeaseClient", ] diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_directory_client_async.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_directory_client_async.py index b4fb7ff46333..ef985df17585 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_directory_client_async.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_directory_client_async.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -10,10 +11,7 @@ import time import warnings from datetime import datetime -from typing import ( - Any, AnyStr, AsyncIterable, cast, Dict, IO, Iterable, Optional, Union, - TYPE_CHECKING -) +from typing import Any, AnyStr, AsyncIterable, cast, Dict, IO, Iterable, Optional, Union, TYPE_CHECKING from typing_extensions import Self from azure.core.async_paging import AsyncItemPaged @@ -22,13 +20,9 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from .._deserialize import deserialize_directory_properties -from .._directory_client_helpers import ( - _format_url, - _from_directory_url, - _parse_url -) -from .._generated.aio import AzureFileStorage -from .._parser import _datetime_to_str, _get_file_permission, _parse_snapshot +from .._directory_client_helpers import _format_url, _from_directory_url, _parse_url +from .._generated.aio import FileClient as AzureFileStorage +from .._parser import _datetime_to_str, _get_file_permission, _parse_snapshot, _strip_snapshot_from_url from .._serialize import get_api_version, get_dest_access_conditions, get_rename_smb_properties from .._shared.base_client import parse_query, StorageAccountHostsMixin from .._shared.base_client_async import parse_connection_str, AsyncStorageAccountHostsMixin, AsyncTransportWrapper @@ -104,47 +98,49 @@ class ShareDirectoryClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMix authentication. Only has an effect when credential is of type AsyncTokenCredential. The value could be https://storage.azure.com/ (default) or https://.file.core.windows.net. """ + def __init__( - self, account_url: str, + self, + account_url: str, share_name: str, directory_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long *, - token_intent: Optional[Literal['backup']] = None, - **kwargs: Any + token_intent: Optional[Literal["backup"]] = None, + **kwargs: Any, ) -> None: - kwargs['retry_policy'] = kwargs.get('retry_policy') or ExponentialRetry(**kwargs) - loop = kwargs.pop('loop', None) + kwargs["retry_policy"] = kwargs.get("retry_policy") or ExponentialRetry(**kwargs) + loop = kwargs.pop("loop", None) if loop and sys.version_info >= (3, 8): - warnings.warn("The 'loop' parameter was deprecated from asyncio's high-level" - "APIs in Python 3.8 and is no longer supported.", DeprecationWarning) - if hasattr(credential, 'get_token') and not token_intent: + warnings.warn( + "The 'loop' parameter was deprecated from asyncio's high-level" + "APIs in Python 3.8 and is no longer supported.", + DeprecationWarning, + ) + if hasattr(credential, "get_token") and not token_intent: raise ValueError("'token_intent' keyword is required when 'credential' is an AsyncTokenCredential.") parsed_url = _parse_url(account_url, share_name) path_snapshot, sas_token = parse_query(parsed_url.query) if not sas_token and not credential: raise ValueError( - 'You need to provide either an account shared key or SAS token when creating a storage service.') + "You need to provide either an account shared key or SAS token when creating a storage service." + ) self.snapshot = _parse_snapshot(snapshot, path_snapshot) self.share_name = share_name self.directory_path = directory_path - self._query_str, credential = self._format_query_string( - sas_token, credential, share_snapshot=self.snapshot) - super(ShareDirectoryClient, self).__init__( - parsed_url, service='file-share', credential=credential, **kwargs) - self.allow_trailing_dot = kwargs.pop('allow_trailing_dot', None) - self.allow_source_trailing_dot = kwargs.pop('allow_source_trailing_dot', None) + self._query_str, credential = self._format_query_string(sas_token, credential, share_snapshot=self.snapshot) + super(ShareDirectoryClient, self).__init__(parsed_url, service="file-share", credential=credential, **kwargs) + self.allow_trailing_dot = kwargs.pop("allow_trailing_dot", None) + self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( + url=_strip_snapshot_from_url(self.url), version=get_api_version(kwargs), - url=self.url, - base_url=self.url, pipeline=self._pipeline, - allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, - file_request_intent=self.file_request_intent ) async def __aenter__(self) -> Self: @@ -165,10 +161,13 @@ async def close(self) -> None: @classmethod def from_directory_url( - cls, directory_url: str, + cls, + directory_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """Create a ShareDirectoryClient from a directory url. @@ -199,8 +198,13 @@ def from_directory_url( """ account_url, share_name, directory_path, snapshot = _from_directory_url(directory_url, snapshot) return cls( - account_url=account_url, share_name=share_name, directory_path=directory_path, - snapshot=snapshot, credential=credential, **kwargs) + account_url=account_url, + share_name=share_name, + directory_path=directory_path, + snapshot=snapshot, + credential=credential, + **kwargs, + ) def _format_url(self, hostname: str) -> str: """Format the endpoint URL according to the current location mode hostname. @@ -214,11 +218,14 @@ def _format_url(self, hostname: str) -> str: @classmethod def from_connection_string( - cls, conn_str: str, + cls, + conn_str: str, share_name: str, directory_path: str, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """Create ShareDirectoryClient from a Connection String. @@ -245,11 +252,10 @@ def from_connection_string( :returns: A directory client. :rtype: ~azure.storage.fileshare.aio.ShareDirectoryClient """ - account_url, secondary, credential = parse_connection_str(conn_str, credential, 'file') - if 'secondary_hostname' not in kwargs: - kwargs['secondary_hostname'] = secondary - return cls( - account_url, share_name=share_name, directory_path=directory_path, credential=credential, **kwargs) + account_url, secondary, credential = parse_connection_str(conn_str, credential, "file") + if "secondary_hostname" not in kwargs: + kwargs["secondary_hostname"] = secondary + return cls(account_url, share_name=share_name, directory_path=directory_path, credential=credential, **kwargs) def get_file_client(self, file_name: str, **kwargs: Any) -> ShareFileClient: """Get a client to interact with a specific file. @@ -262,18 +268,28 @@ def get_file_client(self, file_name: str, **kwargs: Any) -> ShareFileClient: :rtype: ~azure.storage.fileshare.ShareFileClient """ if self.directory_path: - file_name = self.directory_path.rstrip('/') + "/" + file_name + file_name = self.directory_path.rstrip("/") + "/" + file_name _pipeline = AsyncPipeline( transport=AsyncTransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # type: ignore [arg-type] # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # type: ignore [arg-type] # pylint: disable=protected-access ) return ShareFileClient( - self.url, file_path=file_name, share_name=self.share_name, snapshot=self.snapshot, - credential=self.credential, api_version=self.api_version, _hosts=self._hosts, _configuration=self._config, - _pipeline=_pipeline, _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent, - **kwargs) + self.url, + file_path=file_name, + share_name=self.share_name, + snapshot=self.snapshot, + credential=self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, + **kwargs, + ) def get_subdirectory_client(self, directory_name: str, **kwargs) -> "ShareDirectoryClient": """Get a client to interact with a specific subdirectory. @@ -296,18 +312,28 @@ def get_subdirectory_client(self, directory_name: str, **kwargs) -> "ShareDirect """ directory_path = directory_name if self.directory_path: - directory_path = self.directory_path.rstrip('/') + "/" + directory_name + directory_path = self.directory_path.rstrip("/") + "/" + directory_name _pipeline = AsyncPipeline( transport=AsyncTransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # type: ignore [arg-type] # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # type: ignore [arg-type] # pylint: disable=protected-access ) return ShareDirectoryClient( - self.url, share_name=self.share_name, directory_path=directory_path, snapshot=self.snapshot, - credential=self.credential, api_version=self.api_version, _hosts=self._hosts, _configuration=self._config, - _pipeline=_pipeline, _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent, - **kwargs) + self.url, + share_name=self.share_name, + directory_path=directory_path, + snapshot=self.snapshot, + credential=self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, + **kwargs, + ) @distributed_trace_async async def create_directory(self, **kwargs: Any) -> Dict[str, Any]: @@ -380,31 +406,37 @@ async def create_directory(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 16 :caption: Creates a directory. """ - metadata = kwargs.pop('metadata', None) - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + metadata = kwargs.pop("metadata", None) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) - file_attributes = kwargs.pop('file_attributes', None) - file_creation_time = kwargs.pop('file_creation_time', None) - file_last_write_time = kwargs.pop('file_last_write_time', None) - file_change_time = kwargs.pop('file_change_time', None) - file_permission = kwargs.pop('file_permission', None) - file_permission_key = kwargs.pop('file_permission_key', None) + file_attributes = kwargs.pop("file_attributes", None) + file_creation_time = kwargs.pop("file_creation_time", None) + file_last_write_time = kwargs.pop("file_last_write_time", None) + file_change_time = kwargs.pop("file_change_time", None) + file_permission = kwargs.pop("file_permission", None) + file_permission_key = kwargs.pop("file_permission_key", None) file_permission = _get_file_permission(file_permission, file_permission_key, None) try: - return cast(Dict[str, Any], await self._client.directory.create( - file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - file_permission=file_permission, - file_permission_key=file_permission_key, - timeout=timeout, - cls=return_response_headers, - headers=headers, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.directory.create( + file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, + file_creation_time=_datetime_to_str(file_creation_time), + file_last_write_time=_datetime_to_str(file_last_write_time), + file_change_time=_datetime_to_str(file_change_time), + file_permission=file_permission, + file_permission_key=file_permission_key, + timeout=timeout, + cls=return_response_headers, + headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -430,9 +462,14 @@ async def delete_directory(self, **kwargs: Any) -> None: :dedent: 16 :caption: Deletes a directory. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) try: - await self._client.directory.delete(timeout=timeout, **kwargs) + await self._client.directory.delete( + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) except HttpResponseError as error: process_storage_error(error) @@ -500,40 +537,51 @@ async def rename_directory(self, new_name: str, **kwargs: Any) -> "ShareDirector if not new_name: raise ValueError("Please specify a new directory name.") - new_name = new_name.strip('/') - new_path_and_query = new_name.split('?') + new_name = new_name.strip("/") + new_path_and_query = new_name.split("?") new_dir_path = new_path_and_query[0] if len(new_path_and_query) == 2: - new_dir_sas = new_path_and_query[1] or self._query_str.strip('?') + new_dir_sas = new_path_and_query[1] or self._query_str.strip("?") else: - new_dir_sas = self._query_str.strip('?') + new_dir_sas = self._query_str.strip("?") new_directory_client = ShareDirectoryClient( - f'{self.scheme}://{self.primary_hostname}', self.share_name, new_dir_path, - credential=new_dir_sas or self.credential, api_version=self.api_version, - _hosts=self._hosts, _configuration=self._config, _pipeline=self._pipeline, - _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent + f"{self.scheme}://{self.primary_hostname}", + self.share_name, + new_dir_path, + credential=new_dir_sas or self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=self._pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, ) kwargs.update(get_rename_smb_properties(kwargs)) - timeout = kwargs.pop('timeout', None) - overwrite = kwargs.pop('overwrite', None) - metadata = kwargs.pop('metadata', None) - headers = kwargs.pop('headers', {}) + timeout = kwargs.pop("timeout", None) + overwrite = kwargs.pop("overwrite", None) + metadata = kwargs.pop("metadata", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) - destination_access_conditions = get_dest_access_conditions(kwargs.pop('destination_lease', None)) + destination_access_conditions = get_dest_access_conditions(kwargs.pop("destination_lease", None)) try: await new_directory_client._client.directory.rename( # pylint: disable=protected-access - self.url, + rename_source=self.url, timeout=timeout, replace_if_exists=overwrite, - destination_lease_access_conditions=destination_access_conditions, + destination_lease_id=destination_access_conditions, headers=headers, - **kwargs) + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) return new_directory_client except HttpResponseError as error: @@ -541,9 +589,7 @@ async def rename_directory(self, new_name: str, **kwargs: Any) -> "ShareDirector @distributed_trace def list_directories_and_files( - self, - name_starts_with: Optional[str] = None, - **kwargs: Any + self, name_starts_with: Optional[str] = None, **kwargs: Any ) -> AsyncItemPaged[Union["DirectoryProperties", "FileProperties"]]: """Lists all the directories and files under the directory. @@ -583,16 +629,22 @@ def list_directories_and_files( :dedent: 16 :caption: List directories and files. """ - timeout = kwargs.pop('timeout', None) - results_per_page = kwargs.pop('results_per_page', None) + timeout = kwargs.pop("timeout", None) + results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( self._client.directory.list_files_and_directories_segment, sharesnapshot=self.snapshot, timeout=timeout, - **kwargs) + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) return AsyncItemPaged( - command, prefix=name_starts_with, results_per_page=results_per_page, - page_iterator_class=DirectoryPropertiesPaged) + command, + prefix=name_starts_with, + results_per_page=results_per_page, + page_iterator_class=DirectoryPropertiesPaged, + ) @distributed_trace def list_handles(self, recursive: bool = False, **kwargs: Any) -> AsyncItemPaged["Handle"]: @@ -610,17 +662,18 @@ def list_handles(self, recursive: bool = False, **kwargs: Any) -> AsyncItemPaged :returns: An auto-paging iterable of Handle :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.storage.fileshare.Handle] """ - timeout = kwargs.pop('timeout', None) - results_per_page = kwargs.pop('results_per_page', None) + timeout = kwargs.pop("timeout", None) + results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( self._client.directory.list_handles, sharesnapshot=self.snapshot, timeout=timeout, recursive=recursive, - **kwargs) - return AsyncItemPaged( - command, results_per_page=results_per_page, - page_iterator_class=HandlesPaged) + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) + return AsyncItemPaged(command, results_per_page=results_per_page, page_iterator_class=HandlesPaged) @distributed_trace_async async def exists(self, **kwargs: Any) -> bool: @@ -637,7 +690,12 @@ async def exists(self, **kwargs: Any) -> bool: :rtype: bool """ try: - await self._client.directory.get_properties(**kwargs) + await self._client.directory.get_properties( + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + sharesnapshot=self.snapshot, + **kwargs, + ) return True except HttpResponseError as error: try: @@ -666,20 +724,22 @@ async def close_handle(self, handle: Union[str, "Handle"], **kwargs: Any) -> Dic handle_id = handle.id else: handle_id = handle - if handle_id == '*': + if handle_id == "*": raise ValueError("Handle ID '*' is not supported. Use 'close_all_handles' instead.") try: response = await self._client.directory.force_close_handles( - handle_id, + handle_id=handle_id, marker=None, recursive=None, sharesnapshot=self.snapshot, cls=return_response_headers, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) return { - 'closed_handles_count': response.get('number_of_handles_closed', 0), - 'failed_handles_count': response.get('number_of_handles_failed', 0) + "closed_handles_count": response.get("number_of_handles_closed", 0), + "failed_handles_count": response.get("number_of_handles_failed", 0), } except HttpResponseError as error: process_storage_error(error) @@ -703,7 +763,7 @@ async def close_all_handles(self, recursive: bool = False, **kwargs: Any) -> Dic and the number of handles failed to close in a dict. :rtype: dict[str, int] """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) start_time = time.time() try_close = True @@ -713,26 +773,25 @@ async def close_all_handles(self, recursive: bool = False, **kwargs: Any) -> Dic while try_close: try: response = await self._client.directory.force_close_handles( - handle_id='*', + handle_id="*", timeout=timeout, marker=continuation_token, recursive=recursive, sharesnapshot=self.snapshot, cls=return_response_headers, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) except HttpResponseError as error: process_storage_error(error) - continuation_token = response.get('marker') + continuation_token = response.get("marker") try_close = bool(continuation_token) - total_closed += response.get('number_of_handles_closed', 0) - total_failed += response.get('number_of_handles_failed', 0) + total_closed += response.get("number_of_handles_closed", 0) + total_failed += response.get("number_of_handles_failed", 0) if timeout: timeout = max(0, timeout - (time.time() - start_time)) - return { - 'closed_handles_count': total_closed, - 'failed_handles_count': total_failed - } + return {"closed_handles_count": total_closed, "failed_handles_count": total_failed} @distributed_trace_async async def get_directory_properties(self, **kwargs: Any) -> "DirectoryProperties": @@ -749,12 +808,19 @@ async def get_directory_properties(self, **kwargs: Any) -> "DirectoryProperties" :returns: DirectoryProperties :rtype: ~azure.storage.fileshare.DirectoryProperties """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) try: - response = cast("DirectoryProperties", await self._client.directory.get_properties( - timeout=timeout, - cls=deserialize_directory_properties, - **kwargs)) + response = cast( + "DirectoryProperties", + await self._client.directory.get_properties( + timeout=timeout, + cls=deserialize_directory_properties, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + sharesnapshot=self.snapshot, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) return response @@ -779,26 +845,33 @@ async def set_directory_metadata(self, metadata: Dict[str, Any], **kwargs: Any) :returns: Directory-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], await self._client.directory.set_metadata( - timeout=timeout, - cls=return_response_headers, - headers=headers, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.directory.set_metadata( + timeout=timeout, + cls=return_response_headers, + headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async async def set_http_headers( - self, file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, + self, + file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, file_creation_time: Optional[Union[str, datetime]] = None, file_last_write_time: Optional[Union[str, datetime]] = None, file_permission: Optional[str] = None, permission_key: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """Sets HTTP headers on the directory. @@ -848,20 +921,26 @@ async def set_http_headers( :returns: File-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) file_permission = _get_file_permission(file_permission, permission_key, None) - file_change_time = kwargs.pop('file_change_time', None) + file_change_time = kwargs.pop("file_change_time", None) try: - return cast(Dict[str, Any], await self._client.directory.set_properties( - file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - file_permission=file_permission, - file_permission_key=permission_key, - timeout=timeout, - cls=return_response_headers, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.directory.set_properties( + file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, + file_creation_time=_datetime_to_str(file_creation_time), + file_last_write_time=_datetime_to_str(file_last_write_time), + file_change_time=_datetime_to_str(file_change_time), + file_permission=file_permission, + file_permission_key=permission_key, + timeout=timeout, + cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -893,8 +972,8 @@ async def create_subdirectory(self, directory_name: str, **kwargs: Any) -> "Shar :dedent: 16 :caption: Create a subdirectory. """ - metadata = kwargs.pop('metadata', None) - timeout = kwargs.pop('timeout', None) + metadata = kwargs.pop("metadata", None) + timeout = kwargs.pop("timeout", None) subdir = self.get_subdirectory_client(directory_name) await subdir.create_directory(metadata=metadata, timeout=timeout, **kwargs) return subdir @@ -922,16 +1001,17 @@ async def delete_subdirectory(self, directory_name: str, **kwargs: Any) -> None: :dedent: 16 :caption: Delete a subdirectory. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) subdir = self.get_subdirectory_client(directory_name) await subdir.delete_directory(timeout=timeout, **kwargs) @distributed_trace_async async def upload_file( - self, file_name: str, + self, + file_name: str, data: Union[bytes, str, Iterable[AnyStr], AsyncIterable[AnyStr], IO[AnyStr]], length: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> ShareFileClient: """Creates a new file in the directory and returns a ShareFileClient to interact with the file. @@ -984,10 +1064,7 @@ async def upload_file( :caption: Upload a file to a directory. """ file_client = self.get_file_client(file_name) - await file_client.upload_file( - data, - length=length, - **kwargs) + await file_client.upload_file(data, length=length, **kwargs) return file_client @distributed_trace_async diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_download_async.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_download_async.py index 731e8c86bd92..28023d460a99 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_download_async.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_download_async.py @@ -11,11 +11,7 @@ import warnings from io import BytesIO from itertools import islice -from typing import ( - Any, AsyncIterator, Awaitable, Callable, - cast, Generator, IO, Optional, Tuple, - TYPE_CHECKING -) +from typing import Any, AsyncIterator, Awaitable, Callable, cast, Generator, IO, Optional, Tuple, TYPE_CHECKING from azure.core.exceptions import HttpResponseError, ResourceModifiedError from .._download import _ChunkDownloader @@ -44,8 +40,8 @@ async def process_content(data: Any) -> bytes: class _AsyncChunkDownloader(_ChunkDownloader): def __init__(self, **kwargs: Any) -> None: super(_AsyncChunkDownloader, self).__init__(**kwargs) - self.stream_lock_async = asyncio.Lock() if kwargs.get('parallel') else None - self.progress_lock_async = asyncio.Lock() if kwargs.get('parallel') else None + self.stream_lock_async = asyncio.Lock() if kwargs.get("parallel") else None + self.progress_lock_async = asyncio.Lock() if kwargs.get("parallel") else None async def process_chunk(self, chunk_start: int) -> None: chunk_start, chunk_end = self._calculate_range(chunk_start) @@ -68,7 +64,8 @@ async def _update_progress(self, length: int) -> None: if self.progress_hook: await cast(Callable[[int, Optional[int]], Awaitable[Any]], self.progress_hook)( - self.progress_total, self.total_size) + self.progress_total, self.total_size + ) async def _write_to_stream(self, chunk_data: bytes, chunk_start: int) -> None: if self.stream_lock_async: @@ -80,19 +77,20 @@ async def _write_to_stream(self, chunk_data: bytes, chunk_start: int) -> None: async def _download_chunk(self, chunk_start: int, chunk_end: int) -> bytes: range_header, range_validation = validate_and_format_range_headers( - chunk_start, - chunk_end, - check_content_md5=self.validate_content + chunk_start, chunk_end, check_content_md5=self.validate_content ) try: - _, response = await cast(Awaitable[Any], self.client.download( - range=range_header, - range_get_content_md5=range_validation, - validate_content=self.validate_content, - data_stream_total=self.total_size, - download_stream_current=self.progress_total, - **self.request_options - )) + _, response = await cast( + Awaitable[Any], + self.client.download( + range=range_header, + range_get_content_md5=range_validation, + validate_content=self.validate_content, + data_stream_total=self.total_size, + download_stream_current=self.progress_total, + **self.request_options, + ), + ) if response.properties.etag != self.etag: raise ResourceModifiedError(message="The file has been modified while downloading.") except HttpResponseError as error: @@ -153,7 +151,7 @@ async def __anext__(self) -> bytes: def _get_chunk_data(self) -> bytes: chunk_data = self._current_content[: self._chunk_size] - self._current_content = self._current_content[self._chunk_size:] + self._current_content = self._current_content[self._chunk_size :] return chunk_data @@ -174,7 +172,8 @@ class StorageStreamDownloader: # pylint: disable=too-many-instance-attributes otherwise the total size of the file.""" def __init__( - self, client: "FileOperations" = None, # type: ignore [assignment] + self, + client: "FileOperations" = None, # type: ignore [assignment] config: "StorageConfiguration" = None, # type: ignore [assignment] start_range: Optional[int] = None, end_range: Optional[int] = None, @@ -184,7 +183,7 @@ def __init__( path: str = None, # type: ignore [assignment] share: str = None, # type: ignore [assignment] encoding: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> None: self.name = name self.path = path @@ -198,7 +197,7 @@ def __init__( self._max_concurrency = max_concurrency if max_concurrency is not None else DEFAULT_MAX_CONCURRENCY self._encoding = encoding self._validate_content = validate_content - self._progress_hook = kwargs.pop('progress_hook', None) + self._progress_hook = kwargs.pop("progress_hook", None) self._request_options = kwargs self._location_mode = None self._download_complete = False @@ -210,8 +209,9 @@ def __init__( # The service only provides transactional MD5s for chunks under 4MB. # If validate_content is on, get only self.MAX_CHUNK_GET_SIZE for the first # chunk so a transactional MD5 can be retrieved. - self._first_get_size = self._config.max_single_get_size if not self._validate_content \ - else self._config.max_chunk_get_size + self._first_get_size = ( + self._config.max_single_get_size if not self._validate_content else self._config.max_chunk_get_size + ) initial_request_start = self._start_range or 0 if self._end_range is not None and self._end_range - initial_request_start < self._first_get_size: initial_request_end = self._end_range @@ -235,7 +235,7 @@ async def _setup(self) -> None: self.properties.size = self.size # Overwrite the content range to the user requested range - self.properties.content_range = f'bytes {self._start_range}-{self._end_range}/{self._file_size}' + self.properties.content_range = f"bytes {self._start_range}-{self._end_range}/{self._file_size}" # Overwrite the content MD5 as it is the MD5 for the last range instead # of the stored MD5 @@ -253,17 +253,21 @@ async def _initial_request(self): self._initial_range[1], start_range_required=False, end_range_required=False, - check_content_md5=self._validate_content) + check_content_md5=self._validate_content, + ) try: - location_mode, response = cast(Tuple[Optional[str], Any], await self._client.download( - range=range_header, - range_get_content_md5=range_validation, - validate_content=self._validate_content, - data_stream_total=None, - download_stream_current=0, - **self._request_options - )) + location_mode, response = cast( + Tuple[Optional[str], Any], + await self._client.download( + range=range_header, + range_get_content_md5=range_validation, + validate_content=self._validate_content, + data_stream_total=None, + download_stream_current=0, + **self._request_options, + ), + ) # Check the location we read from to ensure we use the same one # for subsequent requests. @@ -289,12 +293,15 @@ async def _initial_request(self): # request a range, do a regular get request in order to get # any properties. try: - _, response = cast(Tuple[Optional[Any], Any], await self._client.download( - validate_content=self._validate_content, - data_stream_total=0, - download_stream_current=0, - **self._request_options - )) + _, response = cast( + Tuple[Optional[Any], Any], + await self._client.download( + validate_content=self._validate_content, + data_stream_total=0, + download_stream_current=0, + **self._request_options, + ), + ) except HttpResponseError as e: process_storage_error(e) @@ -337,12 +344,13 @@ def chunks(self) -> AsyncIterator[bytes]: validate_content=self._validate_content, use_location=self._location_mode, etag=self._etag, - **self._request_options) + **self._request_options, + ) return _AsyncChunkIterator( size=self.size, content=self._current_content, downloader=iter_downloader, - chunk_size=self._config.max_chunk_get_size + chunk_size=self._config.max_chunk_get_size, ) async def readall(self) -> bytes: @@ -371,10 +379,7 @@ async def content_as_bytes(self, max_concurrency=None): :return: The contents of the file as bytes. :rtype: bytes """ - warnings.warn( - "content_as_bytes is deprecated, use readall instead", - DeprecationWarning - ) + warnings.warn("content_as_bytes is deprecated, use readall instead", DeprecationWarning) self._max_concurrency = max_concurrency if max_concurrency is not None else DEFAULT_MAX_CONCURRENCY return await self.readall() @@ -392,10 +397,7 @@ async def content_as_text(self, max_concurrency=None, encoding="UTF-8"): :return: The contents of the file as a str. :rtype: str """ - warnings.warn( - "content_as_text is deprecated, use readall instead", - DeprecationWarning - ) + warnings.warn("content_as_text is deprecated, use readall instead", DeprecationWarning) self._max_concurrency = max_concurrency if max_concurrency is not None else DEFAULT_MAX_CONCURRENCY self._encoding = encoding return await self.readall() @@ -448,17 +450,16 @@ async def readinto(self, stream: IO[bytes]) -> int: use_location=self._location_mode, progress_hook=self._progress_hook, etag=self._etag, - **self._request_options) + **self._request_options, + ) dl_tasks = downloader.get_chunk_offsets() running_futures = { - asyncio.ensure_future(downloader.process_chunk(d)) - for d in islice(dl_tasks, 0, self._max_concurrency) + asyncio.ensure_future(downloader.process_chunk(d)) for d in islice(dl_tasks, 0, self._max_concurrency) } while running_futures: # Wait for some download to finish before adding a new one - done, running_futures = await asyncio.wait( - running_futures, return_when=asyncio.FIRST_COMPLETED) + done, running_futures = await asyncio.wait(running_futures, return_when=asyncio.FIRST_COMPLETED) try: for task in done: task.result() @@ -495,10 +496,7 @@ async def download_to_stream(self, stream, max_concurrency=None): :returns: The properties of the downloaded file. :rtype: Any """ - warnings.warn( - "download_to_stream is deprecated, use readinto instead", - DeprecationWarning - ) + warnings.warn("download_to_stream is deprecated, use readinto instead", DeprecationWarning) self._max_concurrency = max_concurrency if max_concurrency is not None else DEFAULT_MAX_CONCURRENCY await self.readinto(stream) return self.properties diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_file_client_async.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_file_client_async.py index 45b1a96fefb9..874740552137 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_file_client_async.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_file_client_async.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -12,9 +13,21 @@ from datetime import datetime from io import BytesIO from typing import ( - Any, AnyStr, AsyncGenerator, AsyncIterable, Callable, cast, - Dict, IO, Iterable, List, Literal, Optional, Tuple, Union, - TYPE_CHECKING + Any, + AnyStr, + AsyncGenerator, + AsyncIterable, + Callable, + cast, + Dict, + IO, + Iterable, + List, + Literal, + Optional, + Tuple, + Union, + TYPE_CHECKING, ) from typing_extensions import Self @@ -28,18 +41,17 @@ _from_file_url, _get_ranges_options, _parse_url, - _upload_range_from_url_options + _upload_range_from_url_options, ) -from .._generated.aio import AzureFileStorage -from .._generated.models import FileHTTPHeaders -from .._parser import _datetime_to_str, _get_file_permission, _parse_snapshot +from .._generated.aio import FileClient as AzureFileStorage +from .._parser import _datetime_to_str, _get_file_permission, _parse_snapshot, _strip_snapshot_from_url from .._serialize import ( get_access_conditions, get_api_version, get_dest_access_conditions, get_rename_smb_properties, get_smb_properties, - get_source_access_conditions + get_source_access_conditions, ) from .._shared.base_client import StorageAccountHostsMixin, parse_query from .._shared.base_client_async import AsyncStorageAccountHostsMixin, parse_connection_str @@ -75,20 +87,22 @@ async def _upload_file_helper( file_permission: Optional[str] = None, file_permission_key: Optional[str] = None, progress_hook: Optional[Callable[[int, Optional[int]], None]] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: try: if size is None or size < 0: raise ValueError("A content size must be specified for a File.") response = await client.create_file( - size, content_settings=content_settings, metadata=metadata, + size, + content_settings=content_settings, + metadata=metadata, file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, file_permission=file_permission, permission_key=file_permission_key, timeout=timeout, - **kwargs + **kwargs, ) if size == 0: return response @@ -103,9 +117,9 @@ async def _upload_file_helper( validate_content=validate_content, progress_hook=progress_hook, timeout=timeout, - **kwargs + **kwargs, ) - return cast(Dict[str, Any], sorted(responses, key=lambda r: r.get('last_modified'))[-1]) + return cast(Dict[str, Any], sorted(responses, key=lambda r: r.get("last_modified"))[-1]) except HttpResponseError as error: process_storage_error(error) @@ -162,49 +176,51 @@ class ShareFileClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin): authentication. Only has an effect when credential is of type AsyncTokenCredential. The value could be https://storage.azure.com/ (default) or https://.blob.core.windows.net. """ + def __init__( - self, account_url: str, + self, + account_url: str, share_name: str, file_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long *, - token_intent: Optional[Literal['backup']] = None, - **kwargs: Any + token_intent: Optional[Literal["backup"]] = None, + **kwargs: Any, ) -> None: kwargs["retry_policy"] = kwargs.get("retry_policy") or ExponentialRetry(**kwargs) - loop = kwargs.pop('loop', None) + loop = kwargs.pop("loop", None) if loop and sys.version_info >= (3, 8): - warnings.warn("The 'loop' parameter was deprecated from asyncio's high-level" - "APIs in Python 3.8 and is no longer supported.", DeprecationWarning) - if hasattr(credential, 'get_token') and not token_intent: + warnings.warn( + "The 'loop' parameter was deprecated from asyncio's high-level" + "APIs in Python 3.8 and is no longer supported.", + DeprecationWarning, + ) + if hasattr(credential, "get_token") and not token_intent: raise ValueError("'token_intent' keyword is required when 'credential' is an AsyncTokenCredential.") parsed_url = _parse_url(account_url, share_name, file_path) path_snapshot, sas_token = parse_query(parsed_url.query) if not sas_token and not credential: raise ValueError( - 'You need to provide either an account shared key or SAS token when creating a storage service.') + "You need to provide either an account shared key or SAS token when creating a storage service." + ) self.snapshot = _parse_snapshot(snapshot, path_snapshot) self.share_name = share_name - self.file_path = file_path.split('/') + self.file_path = file_path.split("/") self.file_name = self.file_path[-1] self.directory_path = "/".join(self.file_path[:-1]) - self._query_str, credential = self._format_query_string( - sas_token, credential, share_snapshot=self.snapshot) - super(ShareFileClient, self).__init__( - parsed_url, service='file-share', credential=credential, **kwargs) - self.allow_trailing_dot = kwargs.pop('allow_trailing_dot', None) - self.allow_source_trailing_dot = kwargs.pop('allow_source_trailing_dot', None) + self._query_str, credential = self._format_query_string(sas_token, credential, share_snapshot=self.snapshot) + super(ShareFileClient, self).__init__(parsed_url, service="file-share", credential=credential, **kwargs) + self.allow_trailing_dot = kwargs.pop("allow_trailing_dot", None) + self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( + url=_strip_snapshot_from_url(self.url), version=get_api_version(kwargs), - url=self.url, - base_url=self.url, pipeline=self._pipeline, - allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, - file_request_intent=self.file_request_intent ) async def __aenter__(self) -> Self: @@ -225,10 +241,13 @@ async def close(self) -> None: @classmethod def from_file_url( - cls, file_url: str, + cls, + file_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """A client to interact with a specific file, although that file may not yet exist. @@ -264,12 +283,15 @@ def _format_url(self, hostname: str): @classmethod def from_connection_string( - cls, conn_str: str, + cls, + conn_str: str, share_name: str, file_path: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """Create ShareFileClient from a Connection String. @@ -311,11 +333,12 @@ def from_connection_string( :dedent: 12 :caption: Creates the file client with connection string. """ - account_url, secondary, credential = parse_connection_str(conn_str, credential, 'file') - if 'secondary_hostname' not in kwargs: - kwargs['secondary_hostname'] = secondary + account_url, secondary, credential = parse_connection_str(conn_str, credential, "file") + if "secondary_hostname" not in kwargs: + kwargs["secondary_hostname"] = secondary return cls( - account_url, share_name=share_name, file_path=file_path, snapshot=snapshot, credential=credential, **kwargs) + account_url, share_name=share_name, file_path=file_path, snapshot=snapshot, credential=credential, **kwargs + ) @distributed_trace_async async def acquire_lease(self, lease_id: Optional[str] = None, **kwargs: Any) -> ShareLeaseClient: @@ -337,7 +360,7 @@ async def acquire_lease(self, lease_id: Optional[str] = None, **kwargs: Any) -> :returns: A ShareLeaseClient object. :rtype: ~azure.storage.fileshare.aio.ShareLeaseClient """ - kwargs['lease_duration'] = -1 + kwargs["lease_duration"] = -1 lease = ShareLeaseClient(self, lease_id=lease_id) await lease.acquire(**kwargs) return lease @@ -357,7 +380,12 @@ async def exists(self, **kwargs: Any) -> bool: :rtype: bool """ try: - await self._client.file.get_properties(**kwargs) + await self._client.file.get_properties( + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + sharesnapshot=self.snapshot, + **kwargs, + ) return True except HttpResponseError as error: try: @@ -367,13 +395,14 @@ async def exists(self, **kwargs: Any) -> bool: @distributed_trace_async async def create_file( - self, size: int, + self, + size: int, file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, file_creation_time: Optional[Union[str, datetime]] = None, file_last_write_time: Optional[Union[str, datetime]] = None, file_permission: Optional[str] = None, permission_key: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """Creates a new file. @@ -462,57 +491,63 @@ async def create_file( :dedent: 16 :caption: Create a file. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - content_settings = kwargs.pop('content_settings', None) - metadata = kwargs.pop('metadata', None) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + content_settings = kwargs.pop("content_settings", None) + metadata = kwargs.pop("metadata", None) + timeout = kwargs.pop("timeout", None) headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) - data = kwargs.pop('data', None) - file_http_headers = None + data = kwargs.pop("data", None) + file_http_headers = {} if content_settings: - file_http_headers = FileHTTPHeaders( - file_cache_control=content_settings.cache_control, - file_content_type=content_settings.content_type, - file_content_md5=bytearray(content_settings.content_md5) if content_settings.content_md5 else None, - file_content_encoding=content_settings.content_encoding, - file_content_language=content_settings.content_language, - file_content_disposition=content_settings.content_disposition, - ) + file_http_headers = { + "file_cache_control": content_settings.cache_control, + "file_content_type": content_settings.content_type, + "file_content_md5": bytearray(content_settings.content_md5) if content_settings.content_md5 else None, + "file_content_encoding": content_settings.content_encoding, + "file_content_language": content_settings.content_language, + "file_content_disposition": content_settings.content_disposition, + } file_permission = _get_file_permission(file_permission, permission_key, None) - file_change_time = kwargs.pop('file_change_time', None) + file_change_time = kwargs.pop("file_change_time", None) try: - return cast(Dict[str, Any], await self._client.file.create( - file_content_length=size, - metadata=metadata, - file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - file_permission=file_permission, - file_permission_key=permission_key, - file_http_headers=file_http_headers, - optionalbody=data, - content_length=len(data) if data is not None else None, - lease_access_conditions=access_conditions, - headers=headers, - timeout=timeout, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.create( + file_content_length=size, + metadata=metadata, + file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, + file_creation_time=_datetime_to_str(file_creation_time), + file_last_write_time=_datetime_to_str(file_last_write_time), + file_change_time=_datetime_to_str(file_change_time), + file_permission=file_permission, + file_permission_key=permission_key, + **file_http_headers, + optional_body=data, + content_length=len(data) if data is not None else None, + lease_id=access_conditions, + headers=headers, + timeout=timeout, + cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async async def upload_file( - self, data: Union[bytes, str, Iterable[AnyStr], AsyncIterable[AnyStr], IO[bytes]], + self, + data: Union[bytes, str, Iterable[AnyStr], AsyncIterable[AnyStr], IO[bytes]], length: Optional[int] = None, file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, file_creation_time: Optional[Union[str, datetime]] = None, file_last_write_time: Optional[Union[str, datetime]] = None, file_permission: Optional[str] = None, permission_key: Optional[str] = None, - **kwargs + **kwargs, ) -> Dict[str, Any]: """Uploads a new file. @@ -599,15 +634,15 @@ async def upload_file( :dedent: 16 :caption: Upload a file. """ - metadata = kwargs.pop('metadata', None) - content_settings = kwargs.pop('content_settings', None) - max_concurrency = kwargs.pop('max_concurrency', None) + metadata = kwargs.pop("metadata", None) + content_settings = kwargs.pop("content_settings", None) + max_concurrency = kwargs.pop("max_concurrency", None) if max_concurrency is None: max_concurrency = DEFAULT_MAX_CONCURRENCY - validate_content = kwargs.pop('validate_content', False) - progress_hook = kwargs.pop('progress_hook', None) - timeout = kwargs.pop('timeout', None) - encoding = kwargs.pop('encoding', 'UTF-8') + validate_content = kwargs.pop("validate_content", False) + progress_hook = kwargs.pop("progress_hook", None) + timeout = kwargs.pop("timeout", None) + encoding = kwargs.pop("encoding", "UTF-8") if isinstance(data, str): data = data.encode(encoding) @@ -623,7 +658,7 @@ async def upload_file( stream = data elif hasattr(data, "__iter__"): stream = IterStreamer(data, encoding=encoding) - elif hasattr(data, '__aiter__'): + elif hasattr(data, "__aiter__"): stream = AsyncIterStreamer(cast(AsyncGenerator, data), encoding=encoding) else: raise TypeError(f"Unsupported data type: {type(data)}") @@ -643,7 +678,8 @@ async def upload_file( file_permission=file_permission, file_permission_key=permission_key, progress_hook=progress_hook, - **kwargs) + **kwargs, + ) @distributed_trace_async async def start_copy_from_url(self, source_url: str, **kwargs: Any) -> Dict[str, Any]: @@ -785,32 +821,38 @@ async def start_copy_from_url(self, source_url: str, **kwargs: Any) -> Dict[str, :dedent: 16 :caption: Copy a file from a URL """ - metadata = kwargs.pop('metadata', None) - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) - owner = kwargs.pop('owner', None) - group = kwargs.pop('group', None) - file_mode = kwargs.pop('file_mode', None) - file_mode_copy_mode = kwargs.pop('file_mode_copy_mode', None) - file_owner_copy_mode = kwargs.pop('owner_copy_mode', None) + metadata = kwargs.pop("metadata", None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) + owner = kwargs.pop("owner", None) + group = kwargs.pop("group", None) + file_mode = kwargs.pop("file_mode", None) + file_mode_copy_mode = kwargs.pop("file_mode_copy_mode", None) + file_owner_copy_mode = kwargs.pop("owner_copy_mode", None) headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) kwargs.update(get_smb_properties(kwargs)) try: - return cast(Dict[str, Any], await self._client.file.start_copy( - source_url, - metadata=metadata, - lease_access_conditions=access_conditions, - owner=owner, - group=group, - file_mode=file_mode, - file_mode_copy_mode=file_mode_copy_mode, - file_owner_copy_mode=file_owner_copy_mode, - headers=headers, - cls=return_response_headers, - timeout=timeout, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.start_copy( + copy_source=source_url, + metadata=metadata, + lease_id=access_conditions, + owner=owner, + group=group, + file_mode=file_mode, + file_mode_copy_mode=file_mode_copy_mode, + file_owner_copy_mode=file_owner_copy_mode, + headers=headers, + cls=return_response_headers, + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -840,24 +882,27 @@ async def abort_copy(self, copy_id: Union[str, FileProperties], **kwargs: Any) - #other-client--per-operation-configuration>`__. :rtype: None """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) if isinstance(copy_id, FileProperties): copy_id = copy_id.copy.id elif isinstance(copy_id, Dict): - copy_id = copy_id['copy_id'] + copy_id = copy_id["copy_id"] try: - await self._client.file.abort_copy(copy_id=copy_id, - lease_access_conditions=access_conditions, - timeout=timeout, **kwargs) + await self._client.file.abort_copy( + copyid=copy_id, + lease_id=access_conditions, + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async async def download_file( - self, offset: Optional[int] = None, - length: Optional[int] = None, - **kwargs: Any + self, offset: Optional[int] = None, length: Optional[int] = None, **kwargs: Any ) -> StorageStreamDownloader: """Downloads a file to the StorageStreamDownloader. The readall() method must be used to read all the content or readinto() must be used to download the file into @@ -923,7 +968,13 @@ async def download_file( raise ValueError("Offset value must not be None if length is set.") range_end = offset + length - 1 # Service actually uses an end-range inclusive index - access_conditions = get_access_conditions(kwargs.pop('lease', None)) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + + # download doesn't accept sharesnapshot as a kwarg, inject via params + if self.snapshot: + params = kwargs.pop("params", {}) or {} + params["sharesnapshot"] = self.snapshot + kwargs["params"] = params downloader = StorageStreamDownloader( client=self._client.file, @@ -931,11 +982,13 @@ async def download_file( start_range=offset, end_range=range_end, name=self.file_name, - path='/'.join(self.file_path), + path="/".join(self.file_path), share=self.share_name, - lease_access_conditions=access_conditions, + lease_id=access_conditions, cls=deserialize_file_stream, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) await downloader._setup() # pylint: disable=protected-access return downloader @@ -969,10 +1022,16 @@ async def delete_file(self, **kwargs: Any) -> None: :dedent: 16 :caption: Delete a file. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - await self._client.file.delete(lease_access_conditions=access_conditions, timeout=timeout, **kwargs) + await self._client.file.delete( + lease_id=access_conditions, + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) except HttpResponseError as error: process_storage_error(error) @@ -1051,50 +1110,56 @@ async def rename_file(self, new_name: str, **kwargs: Any) -> "ShareFileClient": if not new_name: raise ValueError("Please specify a new file name.") - new_name = new_name.strip('/') - new_path_and_query = new_name.split('?') + new_name = new_name.strip("/") + new_path_and_query = new_name.split("?") new_file_path = new_path_and_query[0] if len(new_path_and_query) == 2: - new_file_sas = new_path_and_query[1] or self._query_str.strip('?') + new_file_sas = new_path_and_query[1] or self._query_str.strip("?") else: - new_file_sas = self._query_str.strip('?') + new_file_sas = self._query_str.strip("?") new_file_client = ShareFileClient( - f'{self.scheme}://{self.primary_hostname}', self.share_name, new_file_path, - credential=new_file_sas or self.credential, api_version=self.api_version, - _hosts=self._hosts, _configuration=self._config, _pipeline=self._pipeline, - _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent + f"{self.scheme}://{self.primary_hostname}", + self.share_name, + new_file_path, + credential=new_file_sas or self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=self._pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, ) kwargs.update(get_rename_smb_properties(kwargs)) - file_http_headers = None - content_type = kwargs.pop('content_type', None) - if content_type: - file_http_headers = FileHTTPHeaders( - file_content_type=content_type - ) + file_content_type = kwargs.pop("content_type", None) - timeout = kwargs.pop('timeout', None) - overwrite = kwargs.pop('overwrite', None) - metadata = kwargs.pop('metadata', None) - headers = kwargs.pop('headers', {}) + timeout = kwargs.pop("timeout", None) + overwrite = kwargs.pop("overwrite", None) + metadata = kwargs.pop("metadata", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) - source_access_conditions = get_source_access_conditions(kwargs.pop('source_lease', None)) - dest_access_conditions = get_dest_access_conditions(kwargs.pop('destination_lease', None)) + source_access_conditions = get_source_access_conditions(kwargs.pop("source_lease", None)) + dest_access_conditions = get_dest_access_conditions(kwargs.pop("destination_lease", None)) try: await new_file_client._client.file.rename( # pylint: disable=protected-access - self.url, + rename_source=self.url, timeout=timeout, replace_if_exists=overwrite, - file_http_headers=file_http_headers, - source_lease_access_conditions=source_access_conditions, - destination_lease_access_conditions=dest_access_conditions, + file_content_type=file_content_type, + source_lease_id=source_access_conditions, + destination_lease_id=dest_access_conditions, headers=headers, - **kwargs) + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) return new_file_client except HttpResponseError as error: @@ -1121,16 +1186,21 @@ async def get_file_properties(self, **kwargs: Any) -> FileProperties: :returns: FileProperties :rtype: ~azure.storage.fileshare.FileProperties """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - file_props = cast(FileProperties, await self._client.file.get_properties( - sharesnapshot=self.snapshot, - lease_access_conditions=access_conditions, - timeout=timeout, - cls=deserialize_file_properties, - **kwargs - )) + file_props = cast( + FileProperties, + await self._client.file.get_properties( + sharesnapshot=self.snapshot, + lease_id=access_conditions, + timeout=timeout, + cls=deserialize_file_properties, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) file_props.name = self.file_name @@ -1141,13 +1211,14 @@ async def get_file_properties(self, **kwargs: Any) -> FileProperties: @distributed_trace_async async def set_http_headers( - self, content_settings: "ContentSettings", + self, + content_settings: "ContentSettings", file_attributes: Optional[Union[str, "NTFSAttributes"]] = None, file_creation_time: Optional[Union[str, datetime]] = None, file_last_write_time: Optional[Union[str, datetime]] = None, file_permission: Optional[str] = None, permission_key: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """Sets HTTP headers on the file. @@ -1207,34 +1278,39 @@ async def set_http_headers( :returns: File-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) file_content_length = kwargs.pop("size", None) - file_http_headers = FileHTTPHeaders( - file_cache_control=content_settings.cache_control, - file_content_type=content_settings.content_type, - file_content_md5=bytearray(content_settings.content_md5) if content_settings.content_md5 else None, - file_content_encoding=content_settings.content_encoding, - file_content_language=content_settings.content_language, - file_content_disposition=content_settings.content_disposition, - ) + file_http_headers = { + "file_cache_control": content_settings.cache_control, + "file_content_type": content_settings.content_type, + "file_content_md5": bytearray(content_settings.content_md5) if content_settings.content_md5 else None, + "file_content_encoding": content_settings.content_encoding, + "file_content_language": content_settings.content_language, + "file_content_disposition": content_settings.content_disposition, + } file_permission = _get_file_permission(file_permission, permission_key, None) - file_change_time = kwargs.pop('file_change_time', None) + file_change_time = kwargs.pop("file_change_time", None) try: - return cast(Dict[str, Any], await self._client.file.set_http_headers( - file_content_length=file_content_length, - file_http_headers=file_http_headers, - file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, - file_creation_time=_datetime_to_str(file_creation_time), - file_last_write_time=_datetime_to_str(file_last_write_time), - file_change_time=_datetime_to_str(file_change_time), - file_permission=file_permission, - file_permission_key=permission_key, - lease_access_conditions=access_conditions, - timeout=timeout, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.set_http_headers( + file_content_length=file_content_length, + **file_http_headers, + file_attributes=str(file_attributes) if file_attributes is not None else file_attributes, + file_creation_time=_datetime_to_str(file_creation_time), + file_last_write_time=_datetime_to_str(file_last_write_time), + file_change_time=_datetime_to_str(file_change_time), + file_permission=file_permission, + file_permission_key=permission_key, + lease_id=access_conditions, + timeout=timeout, + cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1266,25 +1342,29 @@ async def set_file_metadata(self, metadata: Optional[Dict[str, Any]] = None, **k :returns: File-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], await self._client.file.set_metadata( - metadata=metadata, lease_access_conditions=access_conditions, - timeout=timeout, cls=return_response_headers, headers=headers, **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.set_metadata( + metadata=metadata, + lease_id=access_conditions, + timeout=timeout, + cls=return_response_headers, + headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async - async def upload_range( - self, data: bytes, - offset: int, - length: int, - **kwargs: Any - ) -> Dict[str, Any]: + async def upload_range(self, data: bytes, offset: int, length: int, **kwargs: Any) -> Dict[str, Any]: """Upload a range of bytes to a file. :param bytes data: @@ -1330,37 +1410,39 @@ async def upload_range( :returns: File-updated property dict (Etag and last modified). :rtype: Dict[str, Any] """ - validate_content = kwargs.pop('validate_content', False) - timeout = kwargs.pop('timeout', None) - encoding = kwargs.pop('encoding', 'UTF-8') - file_last_write_mode = kwargs.pop('file_last_write_mode', None) + validate_content = kwargs.pop("validate_content", False) + timeout = kwargs.pop("timeout", None) + encoding = kwargs.pop("encoding", "UTF-8") + file_last_write_mode = kwargs.pop("file_last_write_mode", None) if isinstance(data, str): data = data.encode(encoding) end_range = offset + length - 1 # Reformat to an inclusive range index - content_range = f'bytes={offset}-{end_range}' - access_conditions = get_access_conditions(kwargs.pop('lease', None)) + content_range = f"bytes={offset}-{end_range}" + access_conditions = get_access_conditions(kwargs.pop("lease", None)) try: - return cast(Dict[str, Any], await self._client.file.upload_range( - range=content_range, - content_length=length, - optionalbody=data, - timeout=timeout, - validate_content=validate_content, - file_last_written_mode=file_last_write_mode, - lease_access_conditions=access_conditions, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.upload_range( + range=content_range, + file_range_write="update", + content_length=length, + optional_body=data, + timeout=timeout, + validate_content=validate_content, + file_last_written_mode=file_last_write_mode, + lease_id=access_conditions, + cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async async def upload_range_from_url( - self, source_url: str, - offset: int, - length: int, - source_offset: int, - **kwargs: Any + self, source_url: str, offset: int, length: int, source_offset: int, **kwargs: Any ) -> Dict[str, Any]: """ Writes the bytes from one Azure File endpoint into the specified range of another Azure File endpoint. @@ -1430,12 +1512,11 @@ async def upload_range_from_url( :rtype: dict[str, Any] """ options = _upload_range_from_url_options( - source_url=source_url, - offset=offset, - length=length, - source_offset=source_offset, - **kwargs + source_url=source_url, offset=offset, length=length, source_offset=source_offset, **kwargs ) + options["allow_trailing_dot"] = self.allow_trailing_dot + options["allow_source_trailing_dot"] = self.allow_source_trailing_dot + options["file_request_intent"] = self.file_request_intent try: return cast(Dict[str, Any], await self._client.file.upload_range_from_url(**options)) except HttpResponseError as error: @@ -1443,9 +1524,7 @@ async def upload_range_from_url( @distributed_trace_async async def get_ranges( - self, offset: Optional[int] = None, - length: Optional[int] = None, - **kwargs: Any + self, offset: Optional[int] = None, length: Optional[int] = None, **kwargs: Any ) -> List[Dict[str, int]]: """Returns the list of valid page ranges for a file or snapshot of a file. @@ -1471,25 +1550,24 @@ async def get_ranges( A list of valid ranges. :rtype: List[dict[str, int]] """ - options = _get_ranges_options( - snapshot=self.snapshot, - offset=offset, - length=length, - **kwargs) + options = _get_ranges_options(snapshot=self.snapshot, offset=offset, length=length, **kwargs) + options["allow_trailing_dot"] = self.allow_trailing_dot + options["file_request_intent"] = self.file_request_intent try: ranges = await self._client.file.get_range_list(**options) except HttpResponseError as error: process_storage_error(error) - return [{'start': file_range.start, 'end': file_range.end} for file_range in ranges.ranges] + return [{"start": file_range.start, "end": file_range.end} for file_range in (ranges.ranges or [])] @distributed_trace_async async def get_ranges_diff( - self, previous_sharesnapshot: Union[str, Dict[str, Any]], + self, + previous_sharesnapshot: Union[str, Dict[str, Any]], offset: Optional[int] = None, length: Optional[int] = None, *, include_renames: Optional[bool] = None, - **kwargs: Any + **kwargs: Any, ) -> Tuple[List[Dict[str, int]], List[Dict[str, int]]]: """Returns the list of valid page ranges for a file or snapshot of a file. @@ -1530,7 +1608,10 @@ async def get_ranges_diff( length=length, previous_sharesnapshot=previous_sharesnapshot, support_rename=include_renames, - **kwargs) + **kwargs, + ) + options["allow_trailing_dot"] = self.allow_trailing_dot + options["file_request_intent"] = self.file_request_intent try: ranges = await self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1564,8 +1645,8 @@ async def clear_range(self, offset: int, length: int, **kwargs: Any) -> Dict[str :returns: File-updated property dict (Etag and last modified). :rtype: Dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) if offset is None or offset % 512 != 0: raise ValueError("offset must be an integer that aligns with 512 bytes file size") @@ -1574,16 +1655,21 @@ async def clear_range(self, offset: int, length: int, **kwargs: Any) -> Dict[str end_range = length + offset - 1 # Reformat to an inclusive range index content_range = f"bytes={offset}-{end_range}" try: - return cast(Dict[str, Any], await self._client.file.upload_range( - timeout=timeout, - cls=return_response_headers, - content_length=0, - optionalbody=None, - file_range_write="clear", - range=content_range, - lease_access_conditions=access_conditions, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.upload_range( + timeout=timeout, + cls=return_response_headers, + content_length=0, + optional_body=None, + file_range_write="clear", + range=content_range, + lease_id=access_conditions, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1609,20 +1695,25 @@ async def resize_file(self, size: int, **kwargs: Any) -> Dict[str, Any]: :returns: File-updated property dict (Etag and last modified). :rtype: Dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - return cast(Dict[str, Any], await self._client.file.set_http_headers( - file_content_length=size, - file_attributes=None, - file_creation_time=None, - file_last_write_time=None, - file_permission="preserve", - lease_access_conditions=access_conditions, - cls=return_response_headers, - timeout=timeout, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.set_http_headers( + file_content_length=size, + file_attributes=None, + file_creation_time=None, + file_last_write_time=None, + file_permission="preserve", + lease_id=access_conditions, + cls=return_response_headers, + timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1639,16 +1730,17 @@ def list_handles(self, **kwargs: Any) -> AsyncItemPaged[Handle]: :returns: An auto-paging iterable of Handle :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.storage.fileshare.Handle] """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( self._client.file.list_handles, sharesnapshot=self.snapshot, timeout=timeout, - **kwargs) - return AsyncItemPaged( - command, results_per_page=results_per_page, - page_iterator_class=HandlesPaged) + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, + ) + return AsyncItemPaged(command, results_per_page=results_per_page, page_iterator_class=HandlesPaged) @distributed_trace_async async def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[str, int]: @@ -1672,19 +1764,21 @@ async def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[ handle_id = handle.id else: handle_id = handle - if handle_id == '*': + if handle_id == "*": raise ValueError("Handle ID '*' is not supported. Use 'close_all_handles' instead.") try: response = await self._client.file.force_close_handles( - handle_id, + handle_id=handle_id, marker=None, sharesnapshot=self.snapshot, cls=return_response_headers, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) return { - 'closed_handles_count': response.get('number_of_handles_closed', 0), - 'failed_handles_count': response.get('number_of_handles_failed', 0) + "closed_handles_count": response.get("number_of_handles_closed", 0), + "failed_handles_count": response.get("number_of_handles_failed", 0), } except HttpResponseError as error: process_storage_error(error) @@ -1706,7 +1800,7 @@ async def close_all_handles(self, **kwargs: Any) -> Dict[str, int]: and the number of handles failed to close in a dict. :rtype: dict[str, int] """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) start_time = time.time() try_close = True @@ -1716,33 +1810,33 @@ async def close_all_handles(self, **kwargs: Any) -> Dict[str, int]: while try_close: try: response = await self._client.file.force_close_handles( - handle_id='*', + handle_id="*", timeout=timeout, marker=continuation_token, sharesnapshot=self.snapshot, cls=return_response_headers, - **kwargs + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, + **kwargs, ) except HttpResponseError as error: process_storage_error(error) - continuation_token = response.get('marker') + continuation_token = response.get("marker") try_close = bool(continuation_token) - total_closed += response.get('number_of_handles_closed', 0) - total_failed += response.get('number_of_handles_failed', 0) + total_closed += response.get("number_of_handles_closed", 0) + total_failed += response.get("number_of_handles_failed", 0) if timeout: timeout = max(0, timeout - (time.time() - start_time)) - return { - 'closed_handles_count': total_closed, - 'failed_handles_count': total_failed - } + return {"closed_handles_count": total_closed, "failed_handles_count": total_failed} @distributed_trace_async async def create_hardlink( - self, target: str, + self, + target: str, *, lease: Optional[Union[ShareLeaseClient, str]] = None, timeout: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """NFS only. Creates a hard link to the file specified by path. @@ -1764,19 +1858,24 @@ async def create_hardlink( :rtype: dict[str, Any] """ try: - return cast(Dict[str, Any], await self._client.file.create_hard_link( - target_file=target, - lease_access_conditions=lease, - timeout=timeout, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.create_hard_link( + target_file=target, + lease_id=lease, + timeout=timeout, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async async def create_symlink( - self, target: str, + self, + target: str, *, metadata: Optional[Dict[str, str]] = None, file_creation_time: Optional[Union[str, datetime]] = None, @@ -1785,7 +1884,7 @@ async def create_symlink( group: Optional[str] = None, lease: Optional[Union[ShareLeaseClient, str]] = None, timeout: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> Dict[str, Any]: """NFS only. Creates a symbolic link to the specified file. @@ -1813,28 +1912,27 @@ async def create_symlink( :rtype: dict[str, Any] """ try: - return cast(Dict[str, Any], await self._client.file.create_symbolic_link( - link_text=target, - metadata=metadata, - file_creation_time=file_creation_time, - file_last_write_time=file_last_write_time, - owner=owner, - group=group, - lease_access_conditions=lease, - timeout=timeout, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.create_symbolic_link( + link_text=target, + metadata=metadata, + file_creation_time=file_creation_time, + file_last_write_time=file_last_write_time, + owner=owner, + group=group, + lease_id=lease, + timeout=timeout, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async - async def get_symlink( - self, - *, - timeout: Optional[int] = None, - **kwargs: Any - ) -> Dict[str, Any]: + async def get_symlink(self, *, timeout: Optional[int] = None, **kwargs: Any) -> Dict[str, Any]: """NFS only. Gets the symbolic link for the file client. :keyword int timeout: @@ -1847,10 +1945,14 @@ async def get_symlink( :rtype: dict[str, Any] """ try: - return cast(Dict[str, Any], await self._client.file.get_symbolic_link( - timeout=timeout, - cls=return_response_headers, - **kwargs - )) + return cast( + Dict[str, Any], + await self._client.file.get_symbolic_link( + timeout=timeout, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_lease_async.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_lease_async.py index 440ad12326ca..ae3d3a747743 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_lease_async.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_lease_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -53,18 +54,20 @@ class ShareLeaseClient: # pylint: disable=client-accepts-api-version-keyword This will be `None` if no lease has yet been acquired or modified.""" def __init__( # pylint: disable=missing-client-constructor-parameter-credential, missing-client-constructor-parameter-kwargs - self, client: Union["ShareFileClient", "ShareClient"], - lease_id: Optional[str] = None + self, client: Union["ShareFileClient", "ShareClient"], lease_id: Optional[str] = None ) -> None: self.id = lease_id or str(uuid.uuid4()) self.last_modified = None self.etag = None - if hasattr(client, 'file_name'): + self._file_request_intent = getattr(client, "file_request_intent", None) + if hasattr(client, "file_name"): self._client = client._client.file # type: ignore self._snapshot = None - elif hasattr(client, 'share_name'): + self._allow_trailing_dot = getattr(client, "allow_trailing_dot", None) + elif hasattr(client, "share_name"): self._client = client._client.share self._snapshot = client.snapshot + self._allow_trailing_dot = None else: raise TypeError("Lease must use ShareFileClient or ShareClient.") @@ -100,20 +103,24 @@ async def acquire(self, **kwargs: Any) -> None: :rtype: None """ try: - lease_duration = kwargs.pop('lease_duration', -1) + lease_duration = kwargs.pop("lease_duration", -1) if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot + if self._allow_trailing_dot is not None: + kwargs["allow_trailing_dot"] = self._allow_trailing_dot response = await self._client.acquire_lease( - timeout=kwargs.pop('timeout', None), - duration=lease_duration, + timeout=kwargs.pop("timeout", None), + lease_duration=lease_duration, proposed_lease_id=self.id, + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - self.id = response.get('lease_id') - self.last_modified = response.get('last_modified') - self.etag = response.get('etag') + self.id = response.get("lease_id") + self.last_modified = response.get("last_modified") + self.etag = response.get("etag") @distributed_trace_async async def renew(self, **kwargs: Any) -> None: @@ -140,15 +147,17 @@ async def renew(self, **kwargs: Any) -> None: try: response = await self._client.renew_lease( lease_id=self.id, - timeout=kwargs.pop('timeout', None), + timeout=kwargs.pop("timeout", None), sharesnapshot=self._snapshot, + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - self.etag = response.get('etag') - self.id = response.get('lease_id') - self.last_modified = response.get('last_modified') + self.etag = response.get("etag") + self.id = response.get("lease_id") + self.last_modified = response.get("last_modified") @distributed_trace_async async def release(self, **kwargs: Any) -> None: @@ -166,21 +175,25 @@ async def release(self, **kwargs: Any) -> None: """ try: if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot + if self._allow_trailing_dot is not None: + kwargs["allow_trailing_dot"] = self._allow_trailing_dot response = await self._client.release_lease( lease_id=self.id, - timeout=kwargs.pop('timeout', None), + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - self.etag = response.get('etag') - self.id = response.get('lease_id') - self.last_modified = response.get('last_modified') + self.etag = response.get("etag") + self.id = response.get("lease_id") + self.last_modified = response.get("last_modified") @distributed_trace_async async def change(self, proposed_lease_id: str, **kwargs: Any) -> None: - """ Changes the lease ID of an active lease. A change must include the current lease ID in x-ms-lease-id and + """Changes the lease ID of an active lease. A change must include the current lease ID in x-ms-lease-id and a new lease ID in x-ms-proposed-lease-id. :param str proposed_lease_id: @@ -196,18 +209,22 @@ async def change(self, proposed_lease_id: str, **kwargs: Any) -> None: """ try: if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot + if self._allow_trailing_dot is not None: + kwargs["allow_trailing_dot"] = self._allow_trailing_dot response = await self._client.change_lease( lease_id=self.id, proposed_lease_id=proposed_lease_id, - timeout=kwargs.pop('timeout', None), + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - self.etag = response.get('etag') - self.id = response.get('lease_id') - self.last_modified = response.get('last_modified') + self.etag = response.get("etag") + self.id = response.get("lease_id") + self.last_modified = response.get("last_modified") @distributed_trace_async async def break_lease(self, **kwargs: Any) -> int: @@ -242,18 +259,23 @@ async def break_lease(self, **kwargs: Any) -> int: :rtype: int """ try: - lease_break_period = kwargs.pop('lease_break_period', None) + lease_break_period = kwargs.pop("lease_break_period", None) if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot if isinstance(self._client, ShareOperations): - kwargs['break_period'] = lease_break_period + kwargs["break_period"] = lease_break_period if isinstance(self._client, FileOperations) and lease_break_period: raise TypeError("Setting a lease break period is only applicable to Share leases.") + if self._allow_trailing_dot is not None: + kwargs["allow_trailing_dot"] = self._allow_trailing_dot + response = await self._client.break_lease( - timeout=kwargs.pop('timeout', None), + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, cls=return_response_headers, - **kwargs) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) - return cast(int, response.get('lease_time')) + return cast(int, response.get("lease_time")) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_lease_async.pyi b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_lease_async.pyi index 451f6a9d21ac..b15a5716d707 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_lease_async.pyi +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_lease_async.pyi @@ -15,27 +15,17 @@ from azure.core.tracing.decorator_async import distributed_trace_async from ._file_client_async import ShareFileClient from ._share_client_async import ShareClient - class ShareLeaseClient: id: str etag: Optional[str] last_modified: Optional[datetime] - def __init__( - self, client: Union[ShareFileClient, ShareClient], - lease_id: Optional[str] = None - ) -> None: ... + def __init__(self, client: Union[ShareFileClient, ShareClient], lease_id: Optional[str] = None) -> None: ... async def __aenter__(self) -> Self: ... async def __aexit__( self, typ: Optional[type[BaseException]], exc: Optional[BaseException], tb: Optional[TracebackType] ) -> None: ... @distributed_trace_async - async def acquire( - self, - *, - lease_duration: int = -1, - timeout: Optional[int] = None, - **kwargs: Any - ) -> None: ... + async def acquire(self, *, lease_duration: int = -1, timeout: Optional[int] = None, **kwargs: Any) -> None: ... @distributed_trace_async async def renew(self, *, timeout: Optional[int] = None, **kwargs: Any) -> None: ... @distributed_trace_async @@ -44,9 +34,5 @@ class ShareLeaseClient: async def change(self, proposed_lease_id: str, *, timeout: Optional[int] = None, **kwargs: Any) -> None: ... @distributed_trace_async async def break_lease( - self, - *, - lease_break_period: Optional[int] = None, - timeout: Optional[int] = None, - **kwargs: Any + self, *, lease_break_period: Optional[int] = None, timeout: Optional[int] = None, **kwargs: Any ) -> int: ... diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_models.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_models.py index 4e378e3b8715..35cafac5975f 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_models.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_models.py @@ -5,9 +5,7 @@ # -------------------------------------------------------------------------- # pylint: disable=too-few-public-methods -from typing import ( - Any, Callable, Dict, List, Optional -) +from typing import Any, Callable, Dict, List, Optional from azure.core.async_paging import AsyncPageIterator from azure.core.exceptions import HttpResponseError @@ -19,8 +17,8 @@ def _wrap_item(item): if isinstance(item, DirectoryItem): - return {'name': item.name, 'is_directory': True} - return {'name': item.name, 'size': item.properties.content_length, 'is_directory': False} + return {"name": item.name, "is_directory": True} + return {"name": item.name, "size": item.properties.content_length, "is_directory": False} class SharePropertiesPaged(AsyncPageIterator): @@ -49,15 +47,14 @@ class SharePropertiesPaged(AsyncPageIterator): """The current page of listed results.""" def __init__( - self, command: Callable, + self, + command: Callable, prefix: Optional[str] = None, results_per_page: Optional[int] = None, - continuation_token: Optional[str] = None + continuation_token: Optional[str] = None, ) -> None: super(SharePropertiesPaged, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token or "" + get_next=self._get_next_cb, extract_data=self._extract_data_cb, continuation_token=continuation_token or "" ) self._command = command self.service_endpoint = None @@ -74,7 +71,8 @@ async def _get_next_cb(self, continuation_token): maxresults=self.results_per_page, prefix=self.prefix, cls=return_context_and_deserialized, - use_location=self.location_mode) + use_location=self.location_mode, + ) except HttpResponseError as error: process_storage_error(error) @@ -84,7 +82,9 @@ async def _extract_data_cb(self, get_next_return): self.prefix = self._response.prefix self.marker = self._response.marker self.results_per_page = self._response.max_results - self.current_page = [ShareProperties._from_generated(i) for i in self._response.share_items] # pylint: disable=protected-access + self.current_page = [ + ShareProperties._from_generated(i) for i in self._response.share_items # pylint: disable=protected-access + ] return self._response.next_marker or None, self.current_page @@ -107,14 +107,10 @@ class HandlesPaged(AsyncPageIterator): """The current page of listed results.""" def __init__( - self, command: Callable, - results_per_page: Optional[int] = None, - continuation_token: Optional[str] = None + self, command: Callable, results_per_page: Optional[int] = None, continuation_token: Optional[str] = None ) -> None: super(HandlesPaged, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token or "" + get_next=self._get_next_cb, extract_data=self._extract_data_cb, continuation_token=continuation_token or "" ) self._command = command self.marker = None @@ -128,13 +124,16 @@ async def _get_next_cb(self, continuation_token): marker=continuation_token or None, maxresults=self.results_per_page, cls=return_context_and_deserialized, - use_location=self.location_mode) + use_location=self.location_mode, + ) except HttpResponseError as error: process_storage_error(error) async def _extract_data_cb(self, get_next_return): self.location_mode, self._response = get_next_return - self.current_page = [Handle._from_generated(h) for h in self._response.handle_list] # pylint: disable=protected-access + self.current_page = [ + Handle._from_generated(h) for h in self._response.handle_list # pylint: disable=protected-access + ] return self._response.next_marker or None, self.current_page @@ -168,15 +167,14 @@ class DirectoryPropertiesPaged(AsyncPageIterator): """The current page of listed results.""" def __init__( - self, command: Callable, + self, + command: Callable, prefix: Optional[str] = None, results_per_page: Optional[int] = None, - continuation_token: Optional[str] = None + continuation_token: Optional[str] = None, ) -> None: super(DirectoryPropertiesPaged, self).__init__( - get_next=self._get_next_cb, - extract_data=self._extract_data_cb, - continuation_token=continuation_token or "" + get_next=self._get_next_cb, extract_data=self._extract_data_cb, continuation_token=continuation_token or "" ) self._command = command self.service_endpoint = None @@ -193,7 +191,8 @@ async def _get_next_cb(self, continuation_token): prefix=self.prefix, maxresults=self.results_per_page, cls=return_context_and_deserialized, - use_location=self.location_mode) + use_location=self.location_mode, + ) except HttpResponseError as error: process_storage_error(error) @@ -202,6 +201,14 @@ async def _extract_data_cb(self, get_next_return): self.service_endpoint = self._response.service_endpoint self.marker = self._response.marker self.results_per_page = self._response.max_results - self.current_page = [DirectoryProperties._from_generated(i) for i in self._response.segment.directory_items] # pylint: disable = protected-access - self.current_page.extend([FileProperties._from_generated(i) for i in self._response.segment.file_items]) # pylint: disable = protected-access + self.current_page = [ + DirectoryProperties._from_generated(i) # pylint: disable=protected-access + for i in self._response.segment.directory_items + ] + self.current_page.extend( + [ + FileProperties._from_generated(i) # pylint: disable=protected-access + for i in self._response.segment.file_items + ] + ) return self._response.next_marker or None, self.current_page diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_share_client_async.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_share_client_async.py index 8f6be194dc5c..a4b2360c6181 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_share_client_async.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_share_client_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -7,10 +8,7 @@ import sys import warnings -from typing import ( - Any, cast, Dict, Literal, Optional, Union, - TYPE_CHECKING -) +from typing import Any, cast, Dict, Literal, Optional, Union, TYPE_CHECKING from typing_extensions import Self from azure.core.async_paging import AsyncItemPaged @@ -19,29 +17,16 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from .._deserialize import deserialize_permission, deserialize_share_properties -from .._generated.aio import AzureFileStorage -from .._generated.models import ( - DeleteSnapshotsOptionType, - ShareStats, - SignedIdentifier -) +from .._generated.aio import FileClient as AzureFileStorage +from .._generated.models import DeleteSnapshotsOptionType, ShareStats, SignedIdentifier, SignedIdentifiers from .._models import ShareProtocols -from .._parser import _parse_snapshot -from .._share_client_helpers import ( - _create_permission_for_share_options, - _format_url, - _from_share_url, - _parse_url -) +from .._parser import _parse_snapshot, _strip_snapshot_from_url +from .._share_client_helpers import _create_permission_for_share_options, _format_url, _from_share_url, _parse_url from .._shared.policies_async import ExponentialRetry from .._shared.base_client import parse_query, StorageAccountHostsMixin from .._shared.base_client_async import AsyncStorageAccountHostsMixin, AsyncTransportWrapper, parse_connection_str from .._shared.request_handlers import add_metadata_headers, serialize_iso -from .._shared.response_handlers import ( - process_storage_error, - return_headers_and_deserialized, - return_response_headers -) +from .._shared.response_handlers import process_storage_error, return_headers_and_deserialized, return_response_headers from .._serialize import get_access_conditions, get_api_version from ..aio._lease_async import ShareLeaseClient from ._directory_client_async import ShareDirectoryClient @@ -102,44 +87,48 @@ class ShareClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin): # t The hostname of the secondary endpoint. :keyword int max_range_size: The maximum range size used for a file upload. Defaults to 4*1024*1024. """ + def __init__( - self, account_url: str, + self, + account_url: str, share_name: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long *, - token_intent: Optional[Literal['backup']] = None, + token_intent: Optional[Literal["backup"]] = None, **kwargs: Any ) -> None: - kwargs['retry_policy'] = kwargs.get('retry_policy') or ExponentialRetry(**kwargs) - loop = kwargs.pop('loop', None) + kwargs["retry_policy"] = kwargs.get("retry_policy") or ExponentialRetry(**kwargs) + loop = kwargs.pop("loop", None) if loop and sys.version_info >= (3, 8): - warnings.warn("The 'loop' parameter was deprecated from asyncio's high-level" - "APIs in Python 3.8 and is no longer supported.", DeprecationWarning) - if hasattr(credential, 'get_token') and not token_intent: + warnings.warn( + "The 'loop' parameter was deprecated from asyncio's high-level" + "APIs in Python 3.8 and is no longer supported.", + DeprecationWarning, + ) + if hasattr(credential, "get_token") and not token_intent: raise ValueError("'token_intent' keyword is required when 'credential' is an AsyncTokenCredential.") parsed_url = _parse_url(account_url, share_name) path_snapshot, sas_token = parse_query(parsed_url.query) if not sas_token and not credential: raise ValueError( - 'You need to provide either an account shared key or SAS token when creating a storage service.') + "You need to provide either an account shared key or SAS token when creating a storage service." + ) self.snapshot = _parse_snapshot(snapshot, path_snapshot) self.share_name = share_name self._query_str, credential = self._format_query_string( - sas_token=sas_token, credential=credential, share_snapshot=self.snapshot) - super(ShareClient, self).__init__( - parsed_url=parsed_url, service='file-share', credential=credential, **kwargs) - self.allow_trailing_dot = kwargs.pop('allow_trailing_dot', None) - self.allow_source_trailing_dot = kwargs.pop('allow_source_trailing_dot', None) + sas_token=sas_token, credential=credential, share_snapshot=self.snapshot + ) + super(ShareClient, self).__init__(parsed_url=parsed_url, service="file-share", credential=credential, **kwargs) + self.allow_trailing_dot = kwargs.pop("allow_trailing_dot", None) + self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( + url=_strip_snapshot_from_url(self.url), version=get_api_version(kwargs), - url=self.url, - base_url=self.url, pipeline=self._pipeline, - allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, - file_request_intent=self.file_request_intent ) async def __aenter__(self) -> Self: @@ -160,9 +149,12 @@ async def close(self) -> None: @classmethod def from_share_url( - cls, share_url: str, + cls, + share_url: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long **kwargs: Any ) -> Self: """ @@ -203,10 +195,13 @@ def _format_url(self, hostname: str) -> str: @classmethod def from_connection_string( - cls, conn_str: str, + cls, + conn_str: str, share_name: str, snapshot: Optional[Union[str, Dict[str, Any]]] = None, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long **kwargs: Any ) -> Self: """Create ShareClient from a Connection String. @@ -244,11 +239,10 @@ def from_connection_string( :dedent: 8 :caption: Gets the share client from connection string. """ - account_url, secondary, credential = parse_connection_str(conn_str, credential, 'file') - if 'secondary_hostname' not in kwargs: - kwargs['secondary_hostname'] = secondary - return cls( - account_url, share_name=share_name, snapshot=snapshot, credential=credential, **kwargs) + account_url, secondary, credential = parse_connection_str(conn_str, credential, "file") + if "secondary_hostname" not in kwargs: + kwargs["secondary_hostname"] = secondary + return cls(account_url, share_name=share_name, snapshot=snapshot, credential=credential, **kwargs) def get_directory_client(self, directory_path: Optional[str] = None) -> ShareDirectoryClient: """Get a client to interact with the specified directory. @@ -261,14 +255,24 @@ def get_directory_client(self, directory_path: Optional[str] = None) -> ShareDir """ _pipeline = AsyncPipeline( transport=AsyncTransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # type: ignore [arg-type] # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # type: ignore [arg-type] # pylint: disable=protected-access ) return ShareDirectoryClient( - self.url, share_name=self.share_name, directory_path=directory_path or "", snapshot=self.snapshot, - credential=self.credential, api_version=self.api_version, _hosts=self._hosts, _configuration=self._config, - _pipeline=_pipeline, _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent) + self.url, + share_name=self.share_name, + directory_path=directory_path or "", + snapshot=self.snapshot, + credential=self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, + ) def get_file_client(self, file_path: str) -> ShareFileClient: """Get a client to interact with the specified file. @@ -281,14 +285,24 @@ def get_file_client(self, file_path: str) -> ShareFileClient: """ _pipeline = AsyncPipeline( transport=AsyncTransportWrapper(self._pipeline._transport), # pylint: disable=protected-access - policies=self._pipeline._impl_policies # type: ignore [arg-type] # pylint: disable=protected-access + policies=self._pipeline._impl_policies, # type: ignore [arg-type] # pylint: disable=protected-access ) return ShareFileClient( - self.url, share_name=self.share_name, file_path=file_path, snapshot=self.snapshot, - credential=self.credential, api_version=self.api_version, _hosts=self._hosts, _configuration=self._config, - _pipeline=_pipeline, _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent) + self.url, + share_name=self.share_name, + file_path=file_path, + snapshot=self.snapshot, + credential=self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, + ) @distributed_trace_async async def acquire_lease(self, **kwargs: Any) -> ShareLeaseClient: @@ -317,8 +331,8 @@ async def acquire_lease(self, **kwargs: Any) -> ShareLeaseClient: :returns: A ShareLeaseClient object. :rtype: ~azure.storage.fileshare.ShareLeaseClient """ - kwargs['lease_duration'] = kwargs.pop('lease_duration', -1) - lease_id = kwargs.pop('lease_id', None) + kwargs["lease_duration"] = kwargs.pop("lease_duration", -1) + lease_id = kwargs.pop("lease_id", None) lease = ShareLeaseClient(self, lease_id=lease_id) await lease.acquire(**kwargs) return lease @@ -370,38 +384,43 @@ async def create_share(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 12 :caption: Creates a file share. """ - metadata = kwargs.pop('metadata', None) - quota = kwargs.pop('quota', None) - access_tier = kwargs.pop('access_tier', None) - timeout = kwargs.pop('timeout', None) - root_squash = kwargs.pop('root_squash', None) - protocols = kwargs.pop('protocols', None) - paid_bursting_bandwidth_mibps = kwargs.pop('paid_bursting_bandwidth_mibps', None) - paid_bursting_iops = kwargs.pop('paid_bursting_iops', None) - share_provisioned_iops = kwargs.pop('provisioned_iops', None) - share_provisioned_bandwidth_mibps = kwargs.pop('provisioned_bandwidth_mibps', None) - if protocols and protocols not in ['NFS', 'SMB', ShareProtocols.SMB, ShareProtocols.NFS]: + metadata = kwargs.pop("metadata", None) + quota = kwargs.pop("quota", None) + access_tier = kwargs.pop("access_tier", None) + timeout = kwargs.pop("timeout", None) + root_squash = kwargs.pop("root_squash", None) + protocols = kwargs.pop("protocols", None) + paid_bursting_bandwidth_mibps = kwargs.pop("paid_bursting_bandwidth_mibps", None) + paid_bursting_iops = kwargs.pop("paid_bursting_iops", None) + share_provisioned_iops = kwargs.pop("provisioned_iops", None) + share_provisioned_bandwidth_mibps = kwargs.pop("provisioned_bandwidth_mibps", None) + if protocols and protocols not in ["NFS", "SMB", ShareProtocols.SMB, ShareProtocols.NFS]: raise ValueError("The enabled protocol must be set to either SMB or NFS.") - if root_squash and protocols not in ['NFS', ShareProtocols.NFS]: + if root_squash and protocols not in ["NFS", ShareProtocols.NFS]: raise ValueError("The 'root_squash' keyword can only be used on NFS enabled shares.") - headers = kwargs.pop('headers', {}) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], await self._client.share.create( - timeout=timeout, - metadata=metadata, - quota=quota, - access_tier=access_tier, - root_squash=root_squash, - enabled_protocols=protocols, - paid_bursting_max_bandwidth_mibps=paid_bursting_bandwidth_mibps, - paid_bursting_max_iops=paid_bursting_iops, - share_provisioned_iops=share_provisioned_iops, - share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, - cls=return_response_headers, - headers=headers, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.share.create( + timeout=timeout, + metadata=metadata, + quota=quota, + access_tier=access_tier, + root_squash=root_squash, + enabled_protocols=protocols, + paid_bursting_max_bandwidth_mibps=paid_bursting_bandwidth_mibps, + paid_bursting_max_iops=paid_bursting_iops, + share_provisioned_iops=share_provisioned_iops, + share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, + cls=return_response_headers, + headers=headers, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -438,23 +457,27 @@ async def create_snapshot(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 16 :caption: Creates a snapshot of the file share. """ - metadata = kwargs.pop('metadata', None) - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + metadata = kwargs.pop("metadata", None) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], await self._client.share.create_snapshot( - timeout=timeout, - cls=return_response_headers, - headers=headers, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.share.create_snapshot( + timeout=timeout, + cls=return_response_headers, + headers=headers, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async async def delete_share( - self, delete_snapshots: Optional[Union[bool, Literal['include', 'include-leased']]] = False, - **kwargs: Any + self, delete_snapshots: Optional[Union[bool, Literal["include", "include-leased"]]] = False, **kwargs: Any ) -> None: """Marks the specified share for deletion. The share is later deleted during garbage collection. @@ -488,23 +511,25 @@ async def delete_share( :dedent: 16 :caption: Deletes the share and any snapshots. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) delete_include = None if isinstance(delete_snapshots, bool) and delete_snapshots: delete_include = DeleteSnapshotsOptionType.INCLUDE else: - if delete_snapshots == 'include': + if delete_snapshots == "include": delete_include = DeleteSnapshotsOptionType.INCLUDE - elif delete_snapshots == 'include-leased': + elif delete_snapshots == "include-leased": delete_include = DeleteSnapshotsOptionType.INCLUDE_LEASED try: await self._client.share.delete( timeout=timeout, sharesnapshot=self.snapshot, delete_snapshots=delete_include, - lease_access_conditions=access_conditions, - **kwargs) + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ) except HttpResponseError as error: process_storage_error(error) @@ -540,15 +565,20 @@ async def get_share_properties(self, **kwargs: Any) -> "ShareProperties": :dedent: 16 :caption: Gets the share properties. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - props = cast("ShareProperties", await self._client.share.get_properties( - timeout=timeout, - sharesnapshot=self.snapshot, - cls=deserialize_share_properties, - lease_access_conditions=access_conditions, - **kwargs)) + props = cast( + "ShareProperties", + await self._client.share.get_properties( + timeout=timeout, + sharesnapshot=self.snapshot, + cls=deserialize_share_properties, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) props.name = self.share_name @@ -588,16 +618,21 @@ async def set_share_quota(self, quota: int, **kwargs: Any) -> Dict[str, Any]: :dedent: 16 :caption: Sets the share quota. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - return cast(Dict[str, Any], await self._client.share.set_properties( - timeout=timeout, - quota=quota, - access_tier=None, - cls=return_response_headers, - lease_access_conditions=access_conditions, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.share.set_properties( + timeout=timeout, + quota=quota, + access_tier=None, + cls=return_response_headers, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -644,30 +679,35 @@ async def set_share_properties(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 16 :caption: Sets the share properties. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) - access_tier = kwargs.pop('access_tier', None) - quota = kwargs.pop('quota', None) - root_squash = kwargs.pop('root_squash', None) - paid_bursting_bandwidth_mibps = kwargs.pop('paid_bursting_bandwidth_mibps', None) - paid_bursting_iops = kwargs.pop('paid_bursting_iops', None) - share_provisioned_iops = kwargs.pop('provisioned_iops', None) - share_provisioned_bandwidth_mibps = kwargs.pop('provisioned_bandwidth_mibps', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) + access_tier = kwargs.pop("access_tier", None) + quota = kwargs.pop("quota", None) + root_squash = kwargs.pop("root_squash", None) + paid_bursting_bandwidth_mibps = kwargs.pop("paid_bursting_bandwidth_mibps", None) + paid_bursting_iops = kwargs.pop("paid_bursting_iops", None) + share_provisioned_iops = kwargs.pop("provisioned_iops", None) + share_provisioned_bandwidth_mibps = kwargs.pop("provisioned_bandwidth_mibps", None) if all(parameter is None for parameter in [access_tier, quota, root_squash]): raise ValueError("set_share_properties should be called with at least one parameter.") try: - return cast(Dict[str, Any], await self._client.share.set_properties( - timeout=timeout, - quota=quota, - access_tier=access_tier, - root_squash=root_squash, - lease_access_conditions=access_conditions, - paid_bursting_max_bandwidth_mibps=paid_bursting_bandwidth_mibps, - paid_bursting_max_iops=paid_bursting_iops, - share_provisioned_iops=share_provisioned_iops, - share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, - cls=return_response_headers, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.share.set_properties( + timeout=timeout, + quota=quota, + access_tier=access_tier, + root_squash=root_squash, + lease_id=access_conditions, + paid_bursting_max_bandwidth_mibps=paid_bursting_bandwidth_mibps, + paid_bursting_max_iops=paid_bursting_iops, + share_provisioned_iops=share_provisioned_iops, + share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -708,17 +748,22 @@ async def set_share_metadata(self, metadata: Dict[str, str], **kwargs: Any) -> D :dedent: 16 :caption: Sets the share metadata. """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) - headers = kwargs.pop('headers', {}) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) try: - return cast(Dict[str, Any], await self._client.share.set_metadata( - timeout=timeout, - cls=return_response_headers, - headers=headers, - lease_access_conditions=access_conditions, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.share.set_metadata( + timeout=timeout, + cls=return_response_headers, + headers=headers, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -744,25 +789,29 @@ async def get_share_access_policy(self, **kwargs: Any) -> Dict[str, Any]: :returns: Access policy information in a dict. :rtype: dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: response, identifiers = await self._client.share.get_access_policy( timeout=timeout, cls=return_headers_and_deserialized, - lease_access_conditions=access_conditions, - **kwargs) + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ) except HttpResponseError as error: process_storage_error(error) return { - 'public_access': response.get('share_public_access'), - 'signed_identifiers': identifiers or [] + "public_access": response.get("share_public_access"), + "signed_identifiers": ( + identifiers.items_property if hasattr(identifiers, "items_property") else identifiers + ) + or [], } @distributed_trace_async async def set_share_access_policy( - self, signed_identifiers: Dict[str, "AccessPolicy"], - **kwargs: Any + self, signed_identifiers: Dict[str, "AccessPolicy"], **kwargs: Any ) -> Dict[str, Any]: """Sets the permissions for the share, or stored access policies that may be used with Shared Access Signatures. The permissions @@ -790,12 +839,13 @@ async def set_share_access_policy( :returns: Share-updated property dict (Etag and last modified). :rtype: dict[str, Any] """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) if len(signed_identifiers) > 5: raise ValueError( - 'Too many access policies provided. The server does not support setting ' - 'more than 5 access policies on a single resource.') + "Too many access policies provided. The server does not support setting " + "more than 5 access policies on a single resource." + ) identifiers = [] for key, value in signed_identifiers.items(): if value: @@ -803,12 +853,17 @@ async def set_share_access_policy( value.expiry = serialize_iso(value.expiry) identifiers.append(SignedIdentifier(id=key, access_policy=value)) try: - return cast(Dict[str, Any], await self._client.share.set_access_policy( - share_acl=identifiers or None, - timeout=timeout, - cls=return_response_headers, - lease_access_conditions=access_conditions, - **kwargs)) + return cast( + Dict[str, Any], + await self._client.share.set_access_policy( + share_acl=SignedIdentifiers(items_property=identifiers) if identifiers else None, + timeout=timeout, + cls=return_response_headers, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -836,20 +891,23 @@ async def get_share_stats(self, **kwargs: Any) -> int: :return: The approximate size of the data (in bytes) stored on the share. :rtype: int """ - access_conditions = get_access_conditions(kwargs.pop('lease', None)) - timeout = kwargs.pop('timeout', None) + access_conditions = get_access_conditions(kwargs.pop("lease", None)) + timeout = kwargs.pop("timeout", None) try: - stats = cast(ShareStats, await self._client.share.get_statistics( - timeout=timeout, - lease_access_conditions=access_conditions, - **kwargs)) + stats = cast( + ShareStats, + await self._client.share.get_statistics( + timeout=timeout, lease_id=access_conditions, file_request_intent=self.file_request_intent, **kwargs + ), + ) return stats.share_usage_bytes except HttpResponseError as error: process_storage_error(error) @distributed_trace def list_directories_and_files( - self, directory_name: Optional[str] = None, + self, + directory_name: Optional[str] = None, name_starts_with: Optional[str] = None, marker: Optional[str] = None, **kwargs: Any @@ -898,10 +956,11 @@ def list_directories_and_files( :dedent: 16 :caption: List directories and files in the share. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) directory = self.get_directory_client(directory_name) return directory.list_directories_and_files( - name_starts_with=name_starts_with, marker=marker, timeout=timeout, **kwargs) + name_starts_with=name_starts_with, marker=marker, timeout=timeout, **kwargs + ) @distributed_trace_async async def create_permission_for_share(self, file_permission: str, **kwargs: Any) -> Optional[str]: @@ -925,10 +984,13 @@ async def create_permission_for_share(self, file_permission: str, **kwargs: Any) :returns: A file permission key :rtype: str or None """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) options = _create_permission_for_share_options(file_permission, timeout=timeout, **kwargs) try: - return cast(Optional[str], await self._client.share.create_permission(**options)) + return cast( + Optional[str], + await self._client.share.create_permission(file_request_intent=self.file_request_intent, **options), + ) except HttpResponseError as error: process_storage_error(error) @@ -952,13 +1014,18 @@ async def get_permission_for_share(self, permission_key: str, **kwargs: Any) -> :returns: A file permission (a portable SDDL) :rtype: str """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) try: - return cast(str, await self._client.share.get_permission( - file_permission_key=permission_key, - cls=deserialize_permission, - timeout=timeout, - **kwargs)) + return cast( + str, + await self._client.share.get_permission( + file_permission_key=permission_key, + cls=deserialize_permission, + timeout=timeout, + file_request_intent=self.file_request_intent, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -998,7 +1065,7 @@ async def create_directory(self, directory_name: str, **kwargs: Any) -> ShareDir :rtype: ~azure.storage.fileshare.aio.ShareDirectoryClient """ directory = self.get_directory_client(directory_name) - kwargs.setdefault('merge_span', True) + kwargs.setdefault("merge_span", True) await directory.create_directory(**kwargs) return directory diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_share_service_client_async.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_share_service_client_async.py index 048b8973994c..22e093a60954 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_share_service_client_async.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_share_service_client_async.py @@ -8,10 +8,7 @@ import functools import sys import warnings -from typing import ( - Union, Optional, Any, Dict, List, - TYPE_CHECKING -) +from typing import Union, Optional, Any, Dict, List, TYPE_CHECKING from typing_extensions import Self from azure.core.async_paging import AsyncItemPaged @@ -19,9 +16,10 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.pipeline import AsyncPipeline -from .._generated.aio import AzureFileStorage +from .._generated.aio import FileClient as AzureFileStorage from .._generated.models import KeyInfo, StorageServiceProperties from .._models import CorsRule, service_properties_deserialize, ShareProperties +from .._parser import _strip_snapshot_from_url from .._serialize import get_api_version from .._share_service_client_helpers import _parse_url from .._shared.base_client import StorageAccountHostsMixin, parse_query @@ -100,41 +98,44 @@ class ShareServiceClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin :dedent: 8 :caption: Create the share service client with url and credential. """ + def __init__( - self, account_url: str, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long + self, + account_url: str, + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long *, - token_intent: Optional[Literal['backup']] = None, - **kwargs: Any + token_intent: Optional[Literal["backup"]] = None, + **kwargs: Any, ) -> None: - kwargs['retry_policy'] = kwargs.get('retry_policy') or ExponentialRetry(**kwargs) - loop = kwargs.pop('loop', None) + kwargs["retry_policy"] = kwargs.get("retry_policy") or ExponentialRetry(**kwargs) + loop = kwargs.pop("loop", None) if loop and sys.version_info >= (3, 8): - warnings.warn("The 'loop' parameter was deprecated from asyncio's high-level" - "APIs in Python 3.8 and is no longer supported.", DeprecationWarning) + warnings.warn( + "The 'loop' parameter was deprecated from asyncio's high-level" + "APIs in Python 3.8 and is no longer supported.", + DeprecationWarning, + ) - if hasattr(credential, 'get_token') and not token_intent: + if hasattr(credential, "get_token") and not token_intent: raise ValueError("'token_intent' keyword is required when 'credential' is an AsyncTokenCredential.") parsed_url = _parse_url(account_url=account_url) _, sas_token = parse_query(parsed_url.query) if not sas_token and not credential: raise ValueError( - 'You need to provide either an account shared key or SAS token when creating a storage service.') + "You need to provide either an account shared key or SAS token when creating a storage service." + ) self._query_str, credential = self._format_query_string(sas_token, credential) - super(ShareServiceClient, self).__init__( - parsed_url, service='file-share', credential=credential, **kwargs) - self.allow_trailing_dot = kwargs.pop('allow_trailing_dot', None) - self.allow_source_trailing_dot = kwargs.pop('allow_source_trailing_dot', None) + super(ShareServiceClient, self).__init__(parsed_url, service="file-share", credential=credential, **kwargs) + self.allow_trailing_dot = kwargs.pop("allow_trailing_dot", None) + self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( + url=_strip_snapshot_from_url(self.url), version=get_api_version(kwargs), - url=self.url, - base_url=self.url, pipeline=self._pipeline, - allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, - file_request_intent=self.file_request_intent ) async def __aenter__(self) -> Self: @@ -165,9 +166,12 @@ def _format_url(self, hostname: str) -> str: @classmethod def from_connection_string( - cls, conn_str: str, - credential: Optional[Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"]] = None, # pylint: disable=line-too-long - **kwargs: Any + cls, + conn_str: str, + credential: Optional[ + Union[str, Dict[str, str], "AzureNamedKeyCredential", "AzureSasCredential", "AsyncTokenCredential"] + ] = None, # pylint: disable=line-too-long + **kwargs: Any, ) -> Self: """Create ShareServiceClient from a Connection String. @@ -199,9 +203,9 @@ def from_connection_string( :dedent: 8 :caption: Create the share service client with connection string. """ - account_url, secondary, credential = parse_connection_str(conn_str, credential, 'file') - if 'secondary_hostname' not in kwargs: - kwargs['secondary_hostname'] = secondary + account_url, secondary, credential = parse_connection_str(conn_str, credential, "file") + if "secondary_hostname" not in kwargs: + kwargs["secondary_hostname"] = secondary return cls(account_url, credential=credential, **kwargs) @distributed_trace_async @@ -212,7 +216,7 @@ async def get_user_delegation_key( start: Optional["datetime"] = None, delegated_user_tid: Optional[str] = None, timeout: Optional[int] = None, - **kwargs: Any + **kwargs: Any, ) -> "UserDelegationKey": """ Obtain a user delegation key for the purpose of signing SAS tokens. @@ -236,15 +240,11 @@ async def get_user_delegation_key( :rtype: ~azure.storage.queue.UserDelegationKey """ key_info = KeyInfo( - start=_to_utc_datetime(start), - expiry=_to_utc_datetime(expiry), - delegated_user_tid=delegated_user_tid + start=_to_utc_datetime(start), expiry=_to_utc_datetime(expiry), delegated_user_tid=delegated_user_tid ) try: user_delegation_key = await self._client.service.get_user_delegation_key( # type: ignore - key_info=key_info, - timeout=timeout, - **kwargs + key_info=key_info, timeout=timeout, **kwargs ) except HttpResponseError as error: process_storage_error(error) @@ -274,20 +274,23 @@ async def get_service_properties(self, **kwargs: Any) -> Dict[str, Any]: :dedent: 12 :caption: Get file share service properties. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) try: - service_props = await self._client.service.get_properties(timeout=timeout, **kwargs) + service_props = await self._client.service.get_properties( + timeout=timeout, file_request_intent=self.file_request_intent, **kwargs + ) return service_properties_deserialize(service_props) except HttpResponseError as error: process_storage_error(error) @distributed_trace_async async def set_service_properties( - self, hour_metrics: Optional["Metrics"] = None, + self, + hour_metrics: Optional["Metrics"] = None, minute_metrics: Optional["Metrics"] = None, cors: Optional[List[CorsRule]] = None, protocol: Optional["ShareProtocolSettings"] = None, - **kwargs: Any + **kwargs: Any, ) -> None: """Sets the properties of a storage account's File Share service, including Azure Storage Analytics. If an element (e.g. hour_metrics) is left as None, the @@ -326,24 +329,27 @@ async def set_service_properties( :dedent: 8 :caption: Sets file share service properties. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) props = StorageServiceProperties( hour_metrics=hour_metrics, minute_metrics=minute_metrics, cors=CorsRule._to_generated(cors), # pylint: disable=protected-access - protocol=protocol + protocol=protocol, ) try: - await self._client.service.set_properties(props, timeout=timeout, **kwargs) + await self._client.service.set_properties( + props, timeout=timeout, file_request_intent=self.file_request_intent, **kwargs + ) except HttpResponseError as error: process_storage_error(error) @distributed_trace def list_shares( - self, name_starts_with: Optional[str] = None, + self, + name_starts_with: Optional[str] = None, include_metadata: Optional[bool] = False, include_snapshots: Optional[bool] = False, - **kwargs: Any + **kwargs: Any, ) -> AsyncItemPaged[ShareProperties]: """Returns auto-paging iterable of dict-like ShareProperties under the specified account. The generator will lazily follow the continuation tokens returned by @@ -377,25 +383,30 @@ def list_shares( :dedent: 16 :caption: List shares in the file share service. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) include = [] - include_deleted = kwargs.pop('include_deleted', None) + include_deleted = kwargs.pop("include_deleted", None) if include_deleted: include.append("deleted") if include_metadata: - include.append('metadata') + include.append("metadata") if include_snapshots: - include.append('snapshots') + include.append("snapshots") - results_per_page = kwargs.pop('results_per_page', None) + results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( self._client.service.list_shares_segment, include=include, timeout=timeout, - **kwargs) + file_request_intent=self.file_request_intent, + **kwargs, + ) return AsyncItemPaged( - command, prefix=name_starts_with, results_per_page=results_per_page, - page_iterator_class=SharePropertiesPaged) + command, + prefix=name_starts_with, + results_per_page=results_per_page, + page_iterator_class=SharePropertiesPaged, + ) @distributed_trace_async async def create_share(self, share_name: str, **kwargs: Any) -> ShareClient: @@ -429,28 +440,26 @@ async def create_share(self, share_name: str, **kwargs: Any) -> ShareClient: :dedent: 12 :caption: Create a share in the file share service. """ - metadata = kwargs.pop('metadata', None) - quota = kwargs.pop('quota', None) - timeout = kwargs.pop('timeout', None) - provisioned_iops = kwargs.pop('provisioned_iops', None) - provisioned_bandwidth_mibps = kwargs.pop('provisioned_bandwidth_mibps', None) + metadata = kwargs.pop("metadata", None) + quota = kwargs.pop("quota", None) + timeout = kwargs.pop("timeout", None) + provisioned_iops = kwargs.pop("provisioned_iops", None) + provisioned_bandwidth_mibps = kwargs.pop("provisioned_bandwidth_mibps", None) share = self.get_share_client(share_name) - kwargs.setdefault('merge_span', True) + kwargs.setdefault("merge_span", True) await share.create_share( metadata=metadata, quota=quota, timeout=timeout, provisioned_iops=provisioned_iops, provisioned_bandwidth_mibps=provisioned_bandwidth_mibps, - **kwargs + **kwargs, ) return share @distributed_trace_async async def delete_share( - self, share_name: Union[ShareProperties, str], - delete_snapshots: Optional[bool] = False, - **kwargs: Any + self, share_name: Union[ShareProperties, str], delete_snapshots: Optional[bool] = False, **kwargs: Any ) -> None: """Marks the specified share for deletion. The share is later deleted during garbage collection. @@ -478,11 +487,10 @@ async def delete_share( :dedent: 16 :caption: Delete a share in the file share service. """ - timeout = kwargs.pop('timeout', None) + timeout = kwargs.pop("timeout", None) share = self.get_share_client(share_name) - kwargs.setdefault('merge_span', True) - await share.delete_share( - delete_snapshots=delete_snapshots, timeout=timeout, **kwargs) + kwargs.setdefault("merge_span", True) + await share.delete_share(delete_snapshots=delete_snapshots, timeout=timeout, **kwargs) @distributed_trace_async async def undelete_share(self, deleted_share_name: str, deleted_share_version: str, **kwargs: Any) -> ShareClient: @@ -510,16 +518,18 @@ async def undelete_share(self, deleted_share_name: str, deleted_share_version: s """ share = self.get_share_client(deleted_share_name) try: - await share._client.share.restore(deleted_share_name=deleted_share_name, # pylint: disable=protected-access - deleted_share_version=deleted_share_version, - timeout=kwargs.pop('timeout', None), **kwargs) + await share._client.share.restore( # pylint: disable=protected-access + deleted_share_name=deleted_share_name, + deleted_share_version=deleted_share_version, + timeout=kwargs.pop("timeout", None), + **kwargs, + ) return share except HttpResponseError as error: process_storage_error(error) def get_share_client( - self, share: Union[ShareProperties, str], - snapshot: Optional[Union[Dict[str, Any], str]] = None + self, share: Union[ShareProperties, str], snapshot: Optional[Union[Dict[str, Any], str]] = None ) -> ShareClient: """Get a client to interact with the specified share. The share need not already exist. @@ -550,10 +560,19 @@ def get_share_client( _pipeline = AsyncPipeline( transport=AsyncTransportWrapper(self._pipeline._transport), # pylint: disable = protected-access - policies=self._pipeline._impl_policies # type: ignore [arg-type] # pylint: disable = protected-access + policies=self._pipeline._impl_policies, # type: ignore [arg-type] # pylint: disable = protected-access ) return ShareClient( - self.url, share_name=share_name, snapshot=snapshot, credential=self.credential, - api_version=self.api_version, _hosts=self._hosts, _configuration=self._config, - _pipeline=_pipeline, _location_mode=self._location_mode, allow_trailing_dot=self.allow_trailing_dot, - allow_source_trailing_dot=self.allow_source_trailing_dot, token_intent=self.file_request_intent) + self.url, + share_name=share_name, + snapshot=snapshot, + credential=self.credential, + api_version=self.api_version, + _hosts=self._hosts, + _configuration=self._config, + _pipeline=_pipeline, + _location_mode=self._location_mode, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + token_intent=self.file_request_intent, + ) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/py.typed b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/py.typed index e69de29bb2d1..e5aff4f83af8 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/py.typed +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index 08a774b6e206..8bcd9b911dfa 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -1,3 +1,71 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +[build-system] +requires = ["setuptools>=77.0.3", "wheel"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-storage-file-share" +authors = [ + { name = "Microsoft Corporation", email = "ascl@microsoft.com" }, +] +description = "Microsoft Corporation Azure Storage File Share Client Library for Python" +license = "MIT" +classifiers = [ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", +] +requires-python = ">=3.9" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.38.3", + "typing-extensions>=4.6.0", + "cryptography>=2.1.4", +] +dynamic = [ +"version", "readme" +] + +[project.optional-dependencies] +aio = [ + "azure-core[aio]>=1.38.3", +] + +[project.urls] +repository = "https://github.com/Azure/azure-sdk-for-python" + +[tool.setuptools.dynamic] +version = {attr = "azure.storage.fileshare._version.VERSION"} +readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} + +[tool.setuptools.packages.find] +exclude = [ + "tests*", + "generated_tests*", + "samples*", + "generated_samples*", + "doc*", + "azure", + "azure.storage", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] + [tool.azure-sdk-build] mypy = true pyright = false diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_authentication.py b/sdk/storage/azure-storage-file-share/samples/file_samples_authentication.py index b7207e0608da..72ca101ceb5b 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_authentication.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_authentication.py @@ -32,6 +32,7 @@ current_dir = os.path.dirname(os.path.abspath(__file__)) DEST_FILE = os.path.join(current_dir, "SampleDestination.txt") + class FileAuthSamples(object): connection_string = os.getenv("STORAGE_CONNECTION_STRING") @@ -42,55 +43,73 @@ class FileAuthSamples(object): def authentication_connection_string(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: authentication_connection_string") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: authentication_connection_string" + ) sys.exit(1) # Instantiate the ShareServiceClient from a connection string # [START create_share_service_client_from_conn_string] from azure.storage.fileshare import ShareServiceClient + share_service_client = ShareServiceClient.from_connection_string(self.connection_string) # [END create_share_service_client_from_conn_string] def authentication_shared_access_key(self): if self.account_url is None: - print("Missing required environment variable: STORAGE_ACCOUNT_FILE_SHARE_URL." + '\n' + - "Test: authentication_shared_access_key") + print( + "Missing required environment variable: STORAGE_ACCOUNT_FILE_SHARE_URL." + + "\n" + + "Test: authentication_shared_access_key" + ) sys.exit(1) if self.access_key is None: - print("Missing required environment variable: STORAGE_ACCOUNT_KEY." + '\n' + - "Test: authentication_shared_access_key") + print( + "Missing required environment variable: STORAGE_ACCOUNT_KEY." + + "\n" + + "Test: authentication_shared_access_key" + ) sys.exit(1) # Instantiate a ShareServiceClient using a shared access key # [START create_share_service_client] from azure.storage.fileshare import ShareServiceClient - share_service_client = ShareServiceClient( - account_url=self.account_url, - credential=self.access_key - ) + + share_service_client = ShareServiceClient(account_url=self.account_url, credential=self.access_key) # [END create_share_service_client] def authentication_shared_access_signature(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: authentication_shared_access_signature") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: authentication_shared_access_signature" + ) sys.exit(1) if self.account_name is None: - print("Missing required environment variable: STORAGE_ACCOUNT_NAME." + '\n' + - "Test: authentication_shared_access_signature") + print( + "Missing required environment variable: STORAGE_ACCOUNT_NAME." + + "\n" + + "Test: authentication_shared_access_signature" + ) sys.exit(1) if self.access_key is None: - print("Missing required environment variable: STORAGE_ACCOUNT_KEY." + '\n' + - "Test: authentication_shared_access_signature") + print( + "Missing required environment variable: STORAGE_ACCOUNT_KEY." + + "\n" + + "Test: authentication_shared_access_signature" + ) sys.exit(1) # Instantiate a ShareServiceClient using a connection string # [START generate_sas_token] from azure.storage.fileshare import ShareServiceClient + share_service_client = ShareServiceClient.from_connection_string(self.connection_string) # Create a SAS token to use to authenticate a new client @@ -101,14 +120,17 @@ def authentication_shared_access_signature(self): self.access_key, resource_types=ResourceTypes(service=True), permission=AccountSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1) + expiry=datetime.utcnow() + timedelta(hours=1), ) # [END generate_sas_token] def authentication_default_azure_credential(self): if self.account_url is None: - print("Missing required environment variable: STORAGE_ACCOUNT_FILE_SHARE_URL." + '\n' + - "Test: authentication_default_azure_credential") + print( + "Missing required environment variable: STORAGE_ACCOUNT_FILE_SHARE_URL." + + "\n" + + "Test: authentication_default_azure_credential" + ) sys.exit(1) # [START file_share_oauth] @@ -116,32 +138,34 @@ def authentication_default_azure_credential(self): # DefaultAzureCredential attempts a chained set of authentication methods. # See documentation here: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity from azure.identity import DefaultAzureCredential + default_credential = DefaultAzureCredential() # Instantiate a ShareServiceClient using a token credential and token_intent from azure.storage.fileshare import ShareServiceClient + share_service_client = ShareServiceClient( account_url=self.account_url, credential=default_credential, # When using a token credential, you MUST also specify a token_intent - token_intent='backup' + token_intent="backup", ) # Only Directory and File operations, and a certain few Share operations, are currently supported for OAuth. # Create a ShareFileClient from the ShareServiceClient. share_client = share_service_client.get_share_client("myshare") share_client.create_share() - share_client.create_directory('mydirectory') - directory_client = share_client.get_directory_client('mydirectory') + share_client.create_directory("mydirectory") + directory_client = share_client.get_directory_client("mydirectory") with open(DEST_FILE, "wb") as data: - directory_client.upload_file('myfile', data=data) - share_file_client = directory_client.get_file_client('myfile') + directory_client.upload_file("myfile", data=data) + share_file_client = directory_client.get_file_client("myfile") properties = share_file_client.get_file_properties() # [END file_share_oauth] -if __name__ == '__main__': +if __name__ == "__main__": sample = FileAuthSamples() sample.authentication_connection_string() sample.authentication_shared_access_key() diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_authentication_async.py b/sdk/storage/azure-storage-file-share/samples/file_samples_authentication_async.py index 37cfb1546302..021cff228797 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_authentication_async.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_authentication_async.py @@ -33,6 +33,7 @@ current_dir = os.path.dirname(os.path.abspath(__file__)) DEST_FILE = os.path.join(current_dir, "SampleDestination.txt") + class FileAuthSamplesAsync(object): connection_string = os.getenv("STORAGE_CONNECTION_STRING") @@ -43,54 +44,72 @@ class FileAuthSamplesAsync(object): async def authentication_connection_string_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: authentication_connection_string_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: authentication_connection_string_async" + ) sys.exit(1) # Instantiate the ShareServiceClient from a connection string # [START create_share_service_client_from_conn_string] from azure.storage.fileshare.aio import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) # [END create_share_service_client_from_conn_string] async def authentication_shared_access_key_async(self): if self.account_url is None: - print("Missing required environment variable: STORAGE_ACCOUNT_FILE_SHARE_URL." + '\n' + - "Test: authentication_shared_access_key_async") + print( + "Missing required environment variable: STORAGE_ACCOUNT_FILE_SHARE_URL." + + "\n" + + "Test: authentication_shared_access_key_async" + ) sys.exit(1) if self.access_key is None: - print("Missing required environment variable: STORAGE_ACCOUNT_KEY." + '\n' + - "Test: authentication_shared_access_key_async") + print( + "Missing required environment variable: STORAGE_ACCOUNT_KEY." + + "\n" + + "Test: authentication_shared_access_key_async" + ) sys.exit(1) # Instantiate a ShareServiceClient using a shared access key # [START create_share_service_client] from azure.storage.fileshare.aio import ShareServiceClient - share_service_client = ShareServiceClient( - account_url=self.account_url, - credential=self.access_key - ) + + share_service_client = ShareServiceClient(account_url=self.account_url, credential=self.access_key) # [END create_share_service_client] async def authentication_shared_access_signature_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: authentication_shared_access_signature_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: authentication_shared_access_signature_async" + ) sys.exit(1) if self.account_name is None: - print("Missing required environment variable: STORAGE_ACCOUNT_NAME." + '\n' + - "Test: authentication_shared_access_signature_async") + print( + "Missing required environment variable: STORAGE_ACCOUNT_NAME." + + "\n" + + "Test: authentication_shared_access_signature_async" + ) sys.exit(1) if self.access_key is None: - print("Missing required environment variable: STORAGE_ACCOUNT_KEY." + '\n' + - "Test: authentication_shared_access_signature_async") + print( + "Missing required environment variable: STORAGE_ACCOUNT_KEY." + + "\n" + + "Test: authentication_shared_access_signature_async" + ) sys.exit(1) # Instantiate a ShareServiceClient using a connection string from azure.storage.fileshare.aio import ShareServiceClient + share_service_client = ShareServiceClient.from_connection_string(self.connection_string) # Create a SAS token to use to authenticate a new client @@ -101,13 +120,16 @@ async def authentication_shared_access_signature_async(self): self.access_key, resource_types=ResourceTypes(service=True), permission=AccountSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1) + expiry=datetime.utcnow() + timedelta(hours=1), ) async def authentication_default_azure_credential_async(self): if self.account_url is None: - print("Missing required environment variable: STORAGE_ACCOUNT_FILE_SHARE_URL." + '\n' + - "Test: authentication_default_azure_credential_async") + print( + "Missing required environment variable: STORAGE_ACCOUNT_FILE_SHARE_URL." + + "\n" + + "Test: authentication_default_azure_credential_async" + ) sys.exit(1) # [START file_share_oauth] @@ -115,25 +137,27 @@ async def authentication_default_azure_credential_async(self): # DefaultAzureCredential attempts a chained set of authentication methods. # See documentation here: https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity from azure.identity.aio import DefaultAzureCredential + default_credential = DefaultAzureCredential() # Instantiate a ShareServiceClient using a token credential and token_intent from azure.storage.fileshare.aio import ShareServiceClient + share_service_client = ShareServiceClient( account_url=self.account_url, credential=default_credential, # When using a token credential, you MUST also specify a token_intent - token_intent='backup' + token_intent="backup", ) # Only Directory and File operations, and a certain few Share operations, are currently supported for OAuth. # Create a ShareFileClient from the ShareServiceClient. share_client = share_service_client.get_share_client("myshareasync") await share_client.create_share() - await share_client.create_directory('mydirectory') - directory_client = share_client.get_directory_client('mydirectory') + await share_client.create_directory("mydirectory") + directory_client = share_client.get_directory_client("mydirectory") with open(DEST_FILE, "wb") as data: - await directory_client.upload_file('myfile', data=data) - share_file_client = directory_client.get_file_client('myfile') + await directory_client.upload_file("myfile", data=data) + share_file_client = directory_client.get_file_client("myfile") properties = await share_file_client.get_file_properties() # [END file_share_oauth] @@ -146,5 +170,6 @@ async def main(): await sample.authentication_shared_access_signature_async() await sample.authentication_default_azure_credential_async() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_client.py b/sdk/storage/azure-storage-file-share/samples/file_samples_client.py index 0e0f967c8db3..8da3dda6d560 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_client.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_client.py @@ -36,12 +36,16 @@ class FileSamples(object): def simple_file_operations(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: simple_file_operations") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: simple_file_operations" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "filesamples1") # Create the share @@ -82,12 +86,14 @@ def simple_file_operations(self): def copy_file_from_url(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: copy_file_from_url") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + "\n" + "Test: copy_file_from_url" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "filesamples2") # Create the share @@ -104,9 +110,7 @@ def copy_file_from_url(self): # Build the url from which to copy the file source_url = "https://{}.file.core.windows.net/{}/{}".format( - self.account_name, - "filesamples2", - "sourcefile" + self.account_name, "filesamples2", "sourcefile" ) # Copy the sample source file from the url to the destination file @@ -119,12 +123,14 @@ def copy_file_from_url(self): def acquire_file_lease(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: acquire_file_lease") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + "\n" + "Test: acquire_file_lease" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "filesamples3") # Create the share @@ -137,7 +143,7 @@ def acquire_file_lease(self): # [START acquire_and_release_lease_on_file] source_file.create_file(1024) lease = source_file.acquire_lease() - source_file.upload_file(b'hello world', lease=lease) + source_file.upload_file(b"hello world", lease=lease) lease.release() # [END acquire_and_release_lease_on_file] @@ -147,7 +153,7 @@ def acquire_file_lease(self): share.delete_share() -if __name__ == '__main__': +if __name__ == "__main__": sample = FileSamples() sample.simple_file_operations() sample.copy_file_from_url() diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_client_async.py b/sdk/storage/azure-storage-file-share/samples/file_samples_client_async.py index 6b78b23818ea..e7388945dd49 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_client_async.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_client_async.py @@ -38,12 +38,16 @@ class FileSamplesAsync(object): async def simple_file_operations_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: simple_file_operations_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: simple_file_operations_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "filesamples1async") # Create the share @@ -85,12 +89,16 @@ async def simple_file_operations_async(self): async def copy_file_from_url_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: copy_file_from_url_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: copy_file_from_url_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "filesamples2async") # Create the share @@ -108,9 +116,7 @@ async def copy_file_from_url_async(self): # Build the url from which to copy the file source_url = "https://{}.file.core.windows.net/{}/{}".format( - self.account_name, - 'filesamples2async', - 'sourcefile' + self.account_name, "filesamples2async", "sourcefile" ) # Copy the sample source file from the url to the destination file @@ -127,5 +133,6 @@ async def main(): await sample.simple_file_operations_async() await sample.copy_file_from_url_async() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_directory.py b/sdk/storage/azure-storage-file-share/samples/file_samples_directory.py index 756218476608..05e64639acd2 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_directory.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_directory.py @@ -30,16 +30,20 @@ class DirectorySamples(object): - connection_string = os.getenv('STORAGE_CONNECTION_STRING') + connection_string = os.getenv("STORAGE_CONNECTION_STRING") def create_directory_and_file(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_directory_and_file") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_directory_and_file" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "directorysamples1") # Create the share @@ -74,12 +78,16 @@ def create_directory_and_file(self): def create_subdirectory_and_file(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_subdirectory_and_file") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_subdirectory_and_file" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "directorysamples2") # Create the share @@ -123,12 +131,16 @@ def create_subdirectory_and_file(self): def get_subdirectory_client(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: get_subdirectory_client") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: get_subdirectory_client" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "directorysamples3") # Create the share @@ -149,7 +161,7 @@ def get_subdirectory_client(self): share.delete_share() -if __name__ == '__main__': +if __name__ == "__main__": sample = DirectorySamples() sample.create_directory_and_file() sample.create_subdirectory_and_file() diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_directory_async.py b/sdk/storage/azure-storage-file-share/samples/file_samples_directory_async.py index 7455d243f40e..989f7a06761e 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_directory_async.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_directory_async.py @@ -31,16 +31,20 @@ class DirectorySamplesAsync(object): - connection_string = os.getenv('STORAGE_CONNECTION_STRING') + connection_string = os.getenv("STORAGE_CONNECTION_STRING") async def create_directory_and_file_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_directory_and_file_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_directory_and_file_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "directorysamples1async") # Create the share @@ -76,12 +80,16 @@ async def create_directory_and_file_async(self): async def create_subdirectory_and_file_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_subdirectory_and_file_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_subdirectory_and_file_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "directorysamples2async") # Create the share @@ -128,12 +136,16 @@ async def create_subdirectory_and_file_async(self): async def get_subdirectory_client_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: get_subdirectory_client_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: get_subdirectory_client_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "directorysamples3async") # Create the share @@ -161,5 +173,6 @@ async def main(): await sample.create_subdirectory_and_file_async() await sample.get_subdirectory_client_async() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_hello_world.py b/sdk/storage/azure-storage-file-share/samples/file_samples_hello_world.py index c8835ddf4a25..2c5cb80accb5 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_hello_world.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_hello_world.py @@ -30,26 +30,32 @@ class HelloWorldSamples(object): - connection_string = os.getenv('STORAGE_CONNECTION_STRING') + connection_string = os.getenv("STORAGE_CONNECTION_STRING") def create_client_with_connection_string(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_client_with_connection_string") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_client_with_connection_string" + ) sys.exit(1) # Instantiate the ShareServiceClient from a connection string from azure.storage.fileshare import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) def create_file_share(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_file_share") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + "\n" + "Test: create_file_share" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, share_name="helloworld1") # Create the share @@ -66,12 +72,16 @@ def create_file_share(self): def upload_a_file_to_share(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: upload_a_file_to_share") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: upload_a_file_to_share" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, share_name="helloworld2") # Create the share @@ -81,10 +91,10 @@ def upload_a_file_to_share(self): # Instantiate the ShareFileClient from a connection string # [START create_file_client] from azure.storage.fileshare import ShareFileClient + file = ShareFileClient.from_connection_string( - self.connection_string, - share_name="helloworld2", - file_path="myfile") + self.connection_string, share_name="helloworld2", file_path="myfile" + ) # [END create_file_client] # Upload a file @@ -96,7 +106,7 @@ def upload_a_file_to_share(self): share.delete_share() -if __name__ == '__main__': +if __name__ == "__main__": sample = HelloWorldSamples() sample.create_client_with_connection_string() sample.create_file_share() diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_hello_world_async.py b/sdk/storage/azure-storage-file-share/samples/file_samples_hello_world_async.py index 7da6919838b9..41ebb787fa96 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_hello_world_async.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_hello_world_async.py @@ -31,27 +31,34 @@ class HelloWorldSamplesAsync(object): - connection_string = os.getenv('STORAGE_CONNECTION_STRING') + connection_string = os.getenv("STORAGE_CONNECTION_STRING") async def create_client_with_connection_string_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_client_with_connection_string_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_client_with_connection_string_async" + ) sys.exit(1) - # Instantiate the ShareServiceClient from a connection string from azure.storage.fileshare.aio import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) async def create_file_share_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_file_share_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_file_share_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, share_name="helloworld1async") # Create the share @@ -69,13 +76,17 @@ async def create_file_share_async(self): async def upload_a_file_to_share_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: upload_a_file_to_share_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: upload_a_file_to_share_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient - share = ShareClient.from_connection_string(self.connection_string, share_name='helloworld2async') + + share = ShareClient.from_connection_string(self.connection_string, share_name="helloworld2async") # Create the share async with share: @@ -85,10 +96,10 @@ async def upload_a_file_to_share_async(self): # Instantiate the ShareFileClient from a connection string # [START create_file_client] from azure.storage.fileshare.aio import ShareFileClient + file = ShareFileClient.from_connection_string( - self.connection_string, - share_name='helloworld2async', - file_path="myfile") + self.connection_string, share_name="helloworld2async", file_path="myfile" + ) # [END create_file_client] # Upload a file @@ -107,5 +118,6 @@ async def main(): await sample.create_file_share_async() await sample.upload_a_file_to_share_async() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_service.py b/sdk/storage/azure-storage-file-share/samples/file_samples_service.py index 0bb0e5c95961..1675db6bb42c 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_service.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_service.py @@ -31,16 +31,20 @@ class FileShareServiceSamples(object): - connection_string = os.getenv('STORAGE_CONNECTION_STRING') + connection_string = os.getenv("STORAGE_CONNECTION_STRING") def file_service_properties(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: file_service_properties") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: file_service_properties" + ) sys.exit(1) # Instantiate the ShareServiceClient from a connection string from azure.storage.fileshare import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) # [START set_service_properties] @@ -49,13 +53,14 @@ def file_service_properties(self): # Create metrics for requests statistics hour_metrics = Metrics(enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5)) - minute_metrics = Metrics(enabled=True, include_apis=True, - retention_policy=RetentionPolicy(enabled=True, days=5)) + minute_metrics = Metrics( + enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5) + ) # Create CORS rules - cors_rule1 = CorsRule(['www.xyz.com'], ['GET']) - allowed_origins = ['www.xyz.com', "www.ab.com", "www.bc.com"] - allowed_methods = ['GET', 'PUT'] + cors_rule1 = CorsRule(["www.xyz.com"], ["GET"]) + allowed_origins = ["www.xyz.com", "www.ab.com", "www.bc.com"] + allowed_methods = ["GET", "PUT"] max_age_in_seconds = 500 exposed_headers = ["x-ms-meta-data*", "x-ms-meta-source*", "x-ms-meta-abc", "x-ms-meta-bcd"] allowed_headers = ["x-ms-meta-data*", "x-ms-meta-target*", "x-ms-meta-xyz", "x-ms-meta-foo"] @@ -64,7 +69,8 @@ def file_service_properties(self): allowed_methods, max_age_in_seconds=max_age_in_seconds, exposed_headers=exposed_headers, - allowed_headers=allowed_headers) + allowed_headers=allowed_headers, + ) cors = [cors_rule1, cors_rule2] @@ -78,12 +84,16 @@ def file_service_properties(self): def list_shares_in_service(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: list_shares_in_service") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: list_shares_in_service" + ) sys.exit(1) # Instantiate the ShareServiceClient from a connection string from azure.storage.fileshare import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) # [START fsc_create_shares] @@ -106,12 +116,12 @@ def list_shares_in_service(self): def get_share_client(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: get_share_client") + print("Missing required environment variable: STORAGE_CONNECTION_STRING." + "\n" + "Test: get_share_client") sys.exit(1) # [START get_share_client] from azure.storage.fileshare import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) # Get a share client to interact with a specific share @@ -119,7 +129,7 @@ def get_share_client(self): # [END get_share_client] -if __name__ == '__main__': +if __name__ == "__main__": sample = FileShareServiceSamples() sample.file_service_properties() sample.list_shares_in_service() diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_service_async.py b/sdk/storage/azure-storage-file-share/samples/file_samples_service_async.py index 1658aa158b23..2c1d155577d2 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_service_async.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_service_async.py @@ -32,16 +32,20 @@ class FileShareServiceSamplesAsync(object): - connection_string = os.getenv('STORAGE_CONNECTION_STRING') + connection_string = os.getenv("STORAGE_CONNECTION_STRING") async def file_service_properties_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: file_service_properties_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: file_service_properties_async" + ) sys.exit(1) # Instantiate the ShareServiceClient from a connection string from azure.storage.fileshare.aio import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) # [START set_service_properties] @@ -50,13 +54,14 @@ async def file_service_properties_async(self): # Create metrics for requests statistics hour_metrics = Metrics(enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5)) - minute_metrics = Metrics(enabled=True, include_apis=True, - retention_policy=RetentionPolicy(enabled=True, days=5)) + minute_metrics = Metrics( + enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5) + ) # Create CORS rules - cors_rule1 = CorsRule(['www.xyz.com'], ['GET']) - allowed_origins = ['www.xyz.com', "www.ab.com", "www.bc.com"] - allowed_methods = ['GET', 'PUT'] + cors_rule1 = CorsRule(["www.xyz.com"], ["GET"]) + allowed_origins = ["www.xyz.com", "www.ab.com", "www.bc.com"] + allowed_methods = ["GET", "PUT"] max_age_in_seconds = 500 exposed_headers = ["x-ms-meta-data*", "x-ms-meta-source*", "x-ms-meta-abc", "x-ms-meta-bcd"] allowed_headers = ["x-ms-meta-data*", "x-ms-meta-target*", "x-ms-meta-xyz", "x-ms-meta-foo"] @@ -65,14 +70,15 @@ async def file_service_properties_async(self): allowed_methods, max_age_in_seconds=max_age_in_seconds, exposed_headers=exposed_headers, - allowed_headers=allowed_headers) + allowed_headers=allowed_headers, + ) cors = [cors_rule1, cors_rule2] async with file_service: # Set the service properties await file_service.set_service_properties(hour_metrics, minute_metrics, cors) - # [END set_service_properties] + # [END set_service_properties] # [START get_service_properties] properties = await file_service.get_service_properties() @@ -80,12 +86,16 @@ async def file_service_properties_async(self): async def list_shares_in_service_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: list_shares_in_service_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: list_shares_in_service_async" + ) sys.exit(1) # Instantiate the ShareServiceClient from a connection string from azure.storage.fileshare.aio import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) async with file_service: @@ -111,12 +121,16 @@ async def list_shares_in_service_async(self): async def get_share_client_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: get_share_client_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: get_share_client_async" + ) sys.exit(1) # [START get_share_client] from azure.storage.fileshare.aio import ShareServiceClient + file_service = ShareServiceClient.from_connection_string(self.connection_string) # Get a share client to interact with a specific share @@ -130,5 +144,6 @@ async def main(): await sample.list_shares_in_service_async() await sample.get_share_client_async() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_share.py b/sdk/storage/azure-storage-file-share/samples/file_samples_share.py index 21547765cef6..5beb9a3fb812 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_share.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_share.py @@ -33,16 +33,20 @@ class ShareSamples(object): - connection_string = os.getenv('STORAGE_CONNECTION_STRING') + connection_string = os.getenv("STORAGE_CONNECTION_STRING") def create_share_snapshot(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_share_snapshot") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_share_snapshot" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples1") # [START create_share] @@ -60,12 +64,16 @@ def create_share_snapshot(self): def set_share_quota_and_metadata(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: set_share_quota_and_metadata") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: set_share_quota_and_metadata" + ) sys.exit(1) # [START create_share_client_from_conn_string] from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples2") # [END create_share_client_from_conn_string] @@ -79,7 +87,7 @@ def set_share_quota_and_metadata(self): # [END set_share_quota] # [START set_share_metadata] - data = {'category': 'test'} + data = {"category": "test"} share.set_share_metadata(metadata=data) # [END set_share_metadata] @@ -92,11 +100,15 @@ def set_share_quota_and_metadata(self): def set_share_properties(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: set_share_properties") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: set_share_properties" + ) sys.exit(1) from azure.storage.fileshare import ShareClient + share1 = ShareClient.from_connection_string(self.connection_string, "sharesamples3a") share2 = ShareClient.from_connection_string(self.connection_string, "sharesamples3b") @@ -127,12 +139,16 @@ def set_share_properties(self): def list_directories_and_files(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: list_directories_and_files") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: list_directories_and_files" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples4") # Create the share @@ -157,12 +173,16 @@ def list_directories_and_files(self): def get_directory_or_file_client(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: get_directory_or_file_client") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: get_directory_or_file_client" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples5") # Get the directory client to interact with a specific directory @@ -173,12 +193,14 @@ def get_directory_or_file_client(self): def acquire_share_lease(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: acquire_share_lease") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + "\n" + "Test: acquire_share_lease" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples") # Create the share @@ -192,7 +214,7 @@ def acquire_share_lease(self): # [END acquire_and_release_lease_on_share] -if __name__ == '__main__': +if __name__ == "__main__": sample = ShareSamples() sample.create_share_snapshot() sample.set_share_quota_and_metadata() diff --git a/sdk/storage/azure-storage-file-share/samples/file_samples_share_async.py b/sdk/storage/azure-storage-file-share/samples/file_samples_share_async.py index 93aef67615bf..5a8fd8d4cf0f 100644 --- a/sdk/storage/azure-storage-file-share/samples/file_samples_share_async.py +++ b/sdk/storage/azure-storage-file-share/samples/file_samples_share_async.py @@ -34,16 +34,20 @@ class ShareSamplesAsync(object): - connection_string = os.getenv('STORAGE_CONNECTION_STRING') + connection_string = os.getenv("STORAGE_CONNECTION_STRING") async def create_share_snapshot_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: create_share_snapshot_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: create_share_snapshot_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples1async") async with share: @@ -62,12 +66,16 @@ async def create_share_snapshot_async(self): async def set_share_quota_and_metadata_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: set_share_quota_and_metadata_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: set_share_quota_and_metadata_async" + ) sys.exit(1) # [START create_share_client_from_conn_string] from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples2async") # [END create_share_client_from_conn_string] @@ -82,7 +90,7 @@ async def set_share_quota_and_metadata_async(self): # [END set_share_quota] # [START set_share_metadata] - data = {'category': 'test'} + data = {"category": "test"} await share.set_share_metadata(metadata=data) # [END set_share_metadata] @@ -95,11 +103,15 @@ async def set_share_quota_and_metadata_async(self): async def set_share_properties_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: set_share_properties_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: set_share_properties_async" + ) sys.exit(1) from azure.storage.fileshare.aio import ShareClient + share1 = ShareClient.from_connection_string(self.connection_string, "sharesamples3aasync") share2 = ShareClient.from_connection_string(self.connection_string, "sharesamples3basync") @@ -133,12 +145,16 @@ async def set_share_properties_async(self): async def list_directories_and_files_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: list_directories_and_files_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: list_directories_and_files_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples4async") # Create the share @@ -166,12 +182,16 @@ async def list_directories_and_files_async(self): async def get_directory_or_file_client_async(self): if self.connection_string is None: - print("Missing required environment variable: STORAGE_CONNECTION_STRING." + '\n' + - "Test: get_directory_or_file_client_async") + print( + "Missing required environment variable: STORAGE_CONNECTION_STRING." + + "\n" + + "Test: get_directory_or_file_client_async" + ) sys.exit(1) # Instantiate the ShareClient from a connection string from azure.storage.fileshare.aio import ShareClient + share = ShareClient.from_connection_string(self.connection_string, "sharesamples5async") # Get the directory client to interact with a specific directory @@ -189,5 +209,6 @@ async def main(): await sample.list_directories_and_files_async() await sample.get_directory_or_file_client_async() -if __name__ == '__main__': + +if __name__ == "__main__": asyncio.run(main()) diff --git a/sdk/storage/azure-storage-file-share/setup.py b/sdk/storage/azure-storage-file-share/setup.py deleted file mode 100644 index 2e62c6db6a86..000000000000 --- a/sdk/storage/azure-storage-file-share/setup.py +++ /dev/null @@ -1,79 +0,0 @@ -#!/usr/bin/env python - -#------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -#-------------------------------------------------------------------------- - -import re -import os.path -from io import open -from setuptools import find_packages, setup - -# Change the PACKAGE_NAME only to change folder and different name -PACKAGE_NAME = "azure-storage-file-share" -NAMESPACE_NAME = "azure.storage.fileshare" -PACKAGE_PPRINT_NAME = "Azure File Share Storage" - -# a.b.c => a/b/c -package_folder_path = NAMESPACE_NAME.replace('.', '/') - -# Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', - fd.read(), re.MULTILINE).group(1) - -if not version: - raise RuntimeError('Cannot find version information') - -with open('README.md', encoding='utf-8') as f: - readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: - changelog = f.read() - -setup( - name=PACKAGE_NAME, - version=version, - include_package_data=True, - description=f'Microsoft Azure {PACKAGE_PPRINT_NAME} Client Library for Python', - long_description=readme + '\n\n' + changelog, - long_description_content_type='text/markdown', - license='MIT License', - author='Microsoft Corporation', - author_email='ascl@microsoft.com', - url='https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/storage/azure-storage-file-share', - keywords="azure, azure sdk", - classifiers=[ - 'Development Status :: 4 - Beta', - 'Programming Language :: Python', - 'Programming Language :: Python :: 3 :: Only', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: 3.9', - 'Programming Language :: Python :: 3.10', - 'Programming Language :: Python :: 3.11', - 'Programming Language :: Python :: 3.12', - 'Programming Language :: Python :: 3.13', - 'Programming Language :: Python :: 3.14', - 'License :: OSI Approved :: MIT License', - ], - zip_safe=False, - packages=find_packages(exclude=[ - # Exclude packages that will be covered by PEP420 or nspkg - 'azure', - 'azure.storage', - 'tests', - ]), - python_requires=">=3.9", - install_requires=[ - "azure-core>=1.37.0", - "cryptography>=2.1.4", - "typing-extensions>=4.6.0", - "isodate>=0.6.1" - ], - extras_require={ - "aio": [ - "azure-core[aio]>=1.37.0", - ], - }, -) diff --git a/sdk/storage/azure-storage-file-share/tests/conftest.py b/sdk/storage/azure-storage-file-share/tests/conftest.py index cb5378cb35f9..2be8b15e6cf4 100644 --- a/sdk/storage/azure-storage-file-share/tests/conftest.py +++ b/sdk/storage/azure-storage-file-share/tests/conftest.py @@ -15,10 +15,13 @@ add_header_regex_sanitizer, add_oauth_response_sanitizer, add_uri_string_sanitizer, + set_custom_default_matcher, + add_remove_header_sanitizer, add_uri_regex_sanitizer, - test_proxy + test_proxy, ) + @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): subscription_id = os.environ.get("AZURE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") @@ -34,6 +37,11 @@ def add_sanitizers(test_proxy): add_body_regex_sanitizer(regex=r".*?", value="0.0.0.0:0") add_uri_string_sanitizer(target=".preprod.", value=".") + + # TypeSpec-generated code may order query parameters differently than AutoRest + set_custom_default_matcher(ignore_query_ordering=True) + + add_remove_header_sanitizer(headers="Accept") add_uri_regex_sanitizer( regex=r"(?<=[?&]sktid=)[^&#]+", value="00000000-0000-0000-0000-000000000000", diff --git a/sdk/storage/azure-storage-file-share/tests/encryption_test_helper.py b/sdk/storage/azure-storage-file-share/tests/encryption_test_helper.py index 3c25756940cb..23cf5d7aeebc 100644 --- a/sdk/storage/azure-storage-file-share/tests/encryption_test_helper.py +++ b/sdk/storage/azure-storage-file-share/tests/encryption_test_helper.py @@ -21,26 +21,26 @@ class KeyWrapper: - def __init__(self, kid='local:key1'): + def __init__(self, kid="local:key1"): # Must have constant key value for recorded tests, otherwise we could use a random generator. - self.kek = b'\xbe\xa4\x11K\x9eJ\x07\xdafF\x83\xad+\xadvA C\xe8\xbc\x90\xa4\x11}G\xc3\x0f\xd4\xb4\x19m\x11' + self.kek = b"\xbe\xa4\x11K\x9eJ\x07\xdafF\x83\xad+\xadvA C\xe8\xbc\x90\xa4\x11}G\xc3\x0f\xd4\xb4\x19m\x11" self.backend = default_backend() self.kid = kid - def wrap_key(self, key, algorithm='A256KW'): - if algorithm == 'A256KW': + def wrap_key(self, key, algorithm="A256KW"): + if algorithm == "A256KW": return aes_key_wrap(self.kek, key, self.backend) raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM) def unwrap_key(self, key, algorithm): - if algorithm == 'A256KW': + if algorithm == "A256KW": return aes_key_unwrap(self.kek, key, self.backend) raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM) def get_key_wrap_algorithm(self): - return 'A256KW' + return "A256KW" def get_kid(self): return self.kid @@ -58,37 +58,29 @@ def resolve_key(self, kid): class RSAKeyWrapper: - def __init__(self, kid='local:key2'): - self.private_key = generate_private_key(public_exponent=65537, - key_size=2048, - backend=default_backend()) + def __init__(self, kid="local:key2"): + self.private_key = generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) self.public_key = self.private_key.public_key() self.kid = kid - def wrap_key(self, key, algorithm='RSA'): - if algorithm == 'RSA': - return self.public_key.encrypt(key, - OAEP( - mgf=MGF1(algorithm=SHA1()), # nosec - algorithm=SHA1(), # nosec - label=None) - ) + def wrap_key(self, key, algorithm="RSA"): + if algorithm == "RSA": + return self.public_key.encrypt( + key, OAEP(mgf=MGF1(algorithm=SHA1()), algorithm=SHA1(), label=None) # nosec # nosec + ) raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM) def unwrap_key(self, key, algorithm): - if algorithm == 'RSA': - return self.private_key.decrypt(key, - OAEP( - mgf=MGF1(algorithm=SHA1()), # nosec - algorithm=SHA1(), # nosec - label=None) - ) + if algorithm == "RSA": + return self.private_key.decrypt( + key, OAEP(mgf=MGF1(algorithm=SHA1()), algorithm=SHA1(), label=None) # nosec # nosec + ) raise ValueError(_ERROR_UNKNOWN_KEY_WRAP_ALGORITHM) def get_key_wrap_algorithm(self): - return 'RSA' + return "RSA" def get_kid(self): return self.kid diff --git a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/_test_base.py b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/_test_base.py index 0b248d5801ef..e707bd60e59f 100644 --- a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/_test_base.py +++ b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/_test_base.py @@ -3,18 +3,20 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +import os import uuid from devtools_testutils.perfstress_tests import PerfStressTest -from azure.storage.file import FileService # pylint: disable=no-name-in-module +from azure.storage.file import FileService + class _LegacyServiceTest(PerfStressTest): service_client = None async_service_client = None def __init__(self, arguments): - super().__init__(arguments) # pylint: disable=useless-parent-delegation + super().__init__(arguments) connection_string = self.get_from_env("AZURE_STORAGE_CONNECTION_STRING") if not _LegacyServiceTest.service_client or self.args.no_client_share: _LegacyServiceTest.service_client = FileService(connection_string=connection_string) @@ -27,41 +29,36 @@ def __init__(self, arguments): def add_arguments(parser): super(_LegacyServiceTest, _LegacyServiceTest).add_arguments(parser) parser.add_argument( - '-r', - '--max-range-size', - nargs='?', + "-r", + "--max-range-size", + nargs="?", type=int, - help='Maximum size of data uploading in single HTTP PUT. Defaults to 4*1024*1024', - default=4*1024*1024 + help="Maximum size of data uploading in single HTTP PUT. Defaults to 4*1024*1024", + default=4 * 1024 * 1024, ) parser.add_argument( - '-c', - '--max-concurrency', - nargs='?', + "-c", + "--max-concurrency", + nargs="?", type=int, - help='Maximum number of concurrent threads used for data transfer. Defaults to 1', - default=1 + help="Maximum number of concurrent threads used for data transfer. Defaults to 1", + default=1, ) parser.add_argument( - '-s', - '--size', - nargs='?', - type=int, - help='Size of data to transfer. Default is 10240.', - default=10240 + "-s", "--size", nargs="?", type=int, help="Size of data to transfer. Default is 10240.", default=10240 ) parser.add_argument( - '--no-client-share', - action='store_true', - help='Create one ServiceClient per test instance. Default is to share a single ServiceClient.', - default=False + "--no-client-share", + action="store_true", + help="Create one ServiceClient per test instance. Default is to share a single ServiceClient.", + default=False, ) class _LegacyShareTest(_LegacyServiceTest): share_name = "perfstress-legacy-" + str(uuid.uuid4()) - def __init__(self, arguments): # pylint: disable=useless-parent-delegation + def __init__(self, arguments): super().__init__(arguments) async def global_setup(self): diff --git a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/download.py b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/download.py index 1655d95cd073..2783dc073d99 100644 --- a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/download.py +++ b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/download.py @@ -18,10 +18,8 @@ async def global_setup(self): await super().global_setup() data = get_random_bytes(self.args.size) self.service_client.create_file_from_bytes( - share_name=self.share_name, - directory_name=None, - file_name=self.file_name, - file=data) + share_name=self.share_name, directory_name=None, file_name=self.file_name, file=data + ) def run_sync(self): self.download_stream.reset() @@ -30,7 +28,8 @@ def run_sync(self): directory_name=None, file_name=self.file_name, stream=self.download_stream, - max_connections=self.args.max_concurrency) + max_connections=self.args.max_concurrency, + ) async def run_async(self): raise NotImplementedError("Async not supported for legacy T1 tests.") diff --git a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/download_to_file.py b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/download_to_file.py index 08719e5515dc..15dd8242a500 100644 --- a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/download_to_file.py +++ b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/download_to_file.py @@ -19,10 +19,8 @@ async def global_setup(self): await super().global_setup() data = get_random_bytes(self.args.size) self.service_client.create_file_from_bytes( - share_name=self.share_name, - directory_name=None, - file_name=self.file_name, - file=data) + share_name=self.share_name, directory_name=None, file_name=self.file_name, file=data + ) async def setup(self): await super().setup() @@ -38,7 +36,8 @@ def run_sync(self): directory_name=None, file_name=self.file_name, file_path=self.temp_file, - max_connections=self.args.max_concurrency) + max_connections=self.args.max_concurrency, + ) async def run_async(self): raise NotImplementedError("Async not supported for legacy T1 tests.") diff --git a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload.py b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload.py index 077f2fb7abf0..6d6d21fe62e7 100644 --- a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload.py +++ b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload.py @@ -24,7 +24,8 @@ def run_sync(self): file_name=self.file_name, stream=self.upload_stream, count=self.args.size, - max_connections=self.args.max_concurrency) + max_connections=self.args.max_concurrency, + ) async def run_async(self): raise NotImplementedError("Async not supported for legacy T1 tests.") diff --git a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload_from_file.py b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload_from_file.py index 46b121963b75..fb73f2cafcc7 100644 --- a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload_from_file.py +++ b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/T1_legacy_tests/upload_from_file.py @@ -36,7 +36,8 @@ def run_sync(self): directory_name=None, file_name=self.file_name, local_file_path=LegacyUploadFromFileTest.temp_file, - max_connections=self.args.max_concurrency) + max_connections=self.args.max_concurrency, + ) async def run_async(self): raise NotImplementedError("Async not supported for legacy T1 tests.") diff --git a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/_test_base.py b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/_test_base.py index a19693235876..c609f58b8eab 100644 --- a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/_test_base.py +++ b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/_test_base.py @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- +import os import uuid from devtools_testutils.perfstress_tests import PerfStressTest @@ -20,18 +21,16 @@ def __init__(self, arguments): connection_string = self.get_from_env("AZURE_STORAGE_CONNECTION_STRING") kwargs = {} if self.args.max_range_size is not None: - kwargs['max_range_size'] = self.args.max_range_size + kwargs["max_range_size"] = self.args.max_range_size if not _ServiceTest.service_client or self.args.no_client_share: _ServiceTest.service_client = SyncShareServiceClient.from_connection_string( - conn_str=connection_string, - **kwargs + conn_str=connection_string, **kwargs ) _ServiceTest.async_service_client = AsyncShareServiceClient.from_connection_string( - conn_str=connection_string, - **kwargs + conn_str=connection_string, **kwargs ) self.service_client = _ServiceTest.service_client - self.async_service_client =_ServiceTest.async_service_client + self.async_service_client = _ServiceTest.async_service_client async def close(self): await self.async_service_client.close() @@ -41,34 +40,29 @@ async def close(self): def add_arguments(parser): super(_ServiceTest, _ServiceTest).add_arguments(parser) parser.add_argument( - '-r', - '--max-range-size', - nargs='?', + "-r", + "--max-range-size", + nargs="?", type=int, - help='Maximum size of data uploading in single HTTP PUT. Defaults to SDK default.', - default=None + help="Maximum size of data uploading in single HTTP PUT. Defaults to SDK default.", + default=None, ) parser.add_argument( - '-c', - '--max-concurrency', - nargs='?', + "-c", + "--max-concurrency", + nargs="?", type=int, - help='Maximum number of concurrent threads used for data transfer. Defaults to 1', - default=1 + help="Maximum number of concurrent threads used for data transfer. Defaults to 1", + default=1, ) parser.add_argument( - '-s', - '--size', - nargs='?', - type=int, - help='Size of data to transfer. Default is 10240.', - default=10240 + "-s", "--size", nargs="?", type=int, help="Size of data to transfer. Default is 10240.", default=10240 ) parser.add_argument( - '--no-client-share', - action='store_true', - help='Create one ServiceClient per test instance. Default is to share a single ServiceClient.', - default=False + "--no-client-share", + action="store_true", + help="Create one ServiceClient per test instance. Default is to share a single ServiceClient.", + default=False, ) diff --git a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/upload.py b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/upload.py index 7380b321a064..2efe6d1de3f0 100644 --- a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/upload.py +++ b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/upload.py @@ -18,13 +18,11 @@ def __init__(self, arguments): def run_sync(self): self.upload_stream.reset() self.sharefile_client.upload_file( - self.upload_stream, - length=self.args.size, - max_concurrency=self.args.max_concurrency) + self.upload_stream, length=self.args.size, max_concurrency=self.args.max_concurrency + ) async def run_async(self): self.upload_stream_async.reset() await self.async_sharefile_client.upload_file( - self.upload_stream_async, - length=self.args.size, - max_concurrency=self.args.max_concurrency) + self.upload_stream_async, length=self.args.size, max_concurrency=self.args.max_concurrency + ) diff --git a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/upload_from_file.py b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/upload_from_file.py index e113cc804436..781543fcd79e 100644 --- a/sdk/storage/azure-storage-file-share/tests/perfstress_tests/upload_from_file.py +++ b/sdk/storage/azure-storage-file-share/tests/perfstress_tests/upload_from_file.py @@ -27,9 +27,9 @@ async def global_cleanup(self): await super().global_cleanup() def run_sync(self): - with open(UploadFromFileTest.temp_file, 'rb') as fp: + with open(UploadFromFileTest.temp_file, "rb") as fp: self.sharefile_client.upload_file(fp, max_concurrency=self.args.max_concurrency) async def run_async(self): - with open(UploadFromFileTest.temp_file, 'rb') as fp: + with open(UploadFromFileTest.temp_file, "rb") as fp: await self.async_sharefile_client.upload_file(fp, max_concurrency=self.args.max_concurrency) diff --git a/sdk/storage/azure-storage-file-share/tests/settings/settings_fake.py b/sdk/storage/azure-storage-file-share/tests/settings/settings_fake.py index 84dcade5460f..bbd8f1db9757 100644 --- a/sdk/storage/azure-storage-file-share/tests/settings/settings_fake.py +++ b/sdk/storage/azure-storage-file-share/tests/settings/settings_fake.py @@ -11,7 +11,7 @@ SECONDARY_STORAGE_ACCOUNT_NAME = "fakename" SECONDARY_STORAGE_ACCOUNT_KEY = "fakekey" -ACCOUNT_URL_SUFFIX = 'core.windows.net' +ACCOUNT_URL_SUFFIX = "core.windows.net" RUN_IN_LIVE = "False" SKIP_LIVE_RECORDING = "True" diff --git a/sdk/storage/azure-storage-file-share/tests/settings/testcase.py b/sdk/storage/azure-storage-file-share/tests/settings/testcase.py index c0465c4a67ed..99aab3531ddc 100644 --- a/sdk/storage/azure-storage-file-share/tests/settings/testcase.py +++ b/sdk/storage/azure-storage-file-share/tests/settings/testcase.py @@ -4,16 +4,25 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -# pylint: disable=unused-wildcard-import, wildcard-import - from __future__ import division import functools import os.path +try: + import unittest.mock as mock +except ImportError: + import mock + +import logging from devtools_testutils import EnvironmentVariableLoader, EnvironmentVariableOptions from devtools_testutils.fake_credentials import STORAGE_ACCOUNT_FAKE_KEY +try: + from cStringIO import StringIO # Python 2 +except ImportError: + from io import StringIO + try: # Running locally - use configuration in settings_real.py from .settings_real import * @@ -21,27 +30,37 @@ # Running on the pipeline - use fake values in order to create rg, etc. from .settings_fake import * +try: + from devtools_testutils import mgmt_settings_real as settings +except ImportError: + from devtools_testutils import mgmt_settings_fake as settings -LOGGING_FORMAT = '%(asctime)s %(name)-20s %(levelname)-5s %(message)s' -os.environ['STORAGE_ACCOUNT_NAME'] = os.environ.get('STORAGE_ACCOUNT_NAME', None) or STORAGE_ACCOUNT_NAME -os.environ['STORAGE_ACCOUNT_KEY'] = os.environ.get('STORAGE_ACCOUNT_KEY', None) or STORAGE_ACCOUNT_KEY -os.environ['PREMIUM_STORAGE_FILE_ACCOUNT_NAME'] = os.environ.get( - 'PREMIUM_STORAGE_FILE_ACCOUNT_NAME', None) or PREMIUM_STORAGE_FILE_ACCOUNT_NAME -os.environ['PREMIUM_STORAGE_FILE_ACCOUNT_KEY'] = os.environ.get( - 'PREMIUM_STORAGE_FILE_ACCOUNT_KEY', None) or PREMIUM_STORAGE_FILE_ACCOUNT_KEY -os.environ['SECONDARY_STORAGE_ACCOUNT_NAME'] = os.environ.get( - 'SECONDARY_STORAGE_ACCOUNT_NAME', None) or SECONDARY_STORAGE_ACCOUNT_NAME -os.environ['SECONDARY_STORAGE_ACCOUNT_KEY'] = os.environ.get( - 'SECONDARY_STORAGE_ACCOUNT_KEY', None) or SECONDARY_STORAGE_ACCOUNT_KEY -os.environ['AZURE_TEST_RUN_LIVE'] = os.environ.get('AZURE_TEST_RUN_LIVE', None) or RUN_IN_LIVE -os.environ['AZURE_SKIP_LIVE_RECORDING'] = os.environ.get('AZURE_SKIP_LIVE_RECORDING', None) or SKIP_LIVE_RECORDING -os.environ['PROTOCOL'] = PROTOCOL -os.environ['ACCOUNT_URL_SUFFIX'] = ACCOUNT_URL_SUFFIX +LOGGING_FORMAT = "%(asctime)s %(name)-20s %(levelname)-5s %(message)s" +os.environ["STORAGE_ACCOUNT_NAME"] = os.environ.get("STORAGE_ACCOUNT_NAME", None) or STORAGE_ACCOUNT_NAME +os.environ["STORAGE_ACCOUNT_KEY"] = os.environ.get("STORAGE_ACCOUNT_KEY", None) or STORAGE_ACCOUNT_KEY +os.environ["PREMIUM_STORAGE_FILE_ACCOUNT_NAME"] = ( + os.environ.get("PREMIUM_STORAGE_FILE_ACCOUNT_NAME", None) or PREMIUM_STORAGE_FILE_ACCOUNT_NAME +) +os.environ["PREMIUM_STORAGE_FILE_ACCOUNT_KEY"] = ( + os.environ.get("PREMIUM_STORAGE_FILE_ACCOUNT_KEY", None) or PREMIUM_STORAGE_FILE_ACCOUNT_KEY +) +os.environ["SECONDARY_STORAGE_ACCOUNT_NAME"] = ( + os.environ.get("SECONDARY_STORAGE_ACCOUNT_NAME", None) or SECONDARY_STORAGE_ACCOUNT_NAME +) +os.environ["SECONDARY_STORAGE_ACCOUNT_KEY"] = ( + os.environ.get("SECONDARY_STORAGE_ACCOUNT_KEY", None) or SECONDARY_STORAGE_ACCOUNT_KEY +) + +os.environ["AZURE_TEST_RUN_LIVE"] = os.environ.get("AZURE_TEST_RUN_LIVE", None) or RUN_IN_LIVE +os.environ["AZURE_SKIP_LIVE_RECORDING"] = os.environ.get("AZURE_SKIP_LIVE_RECORDING", None) or SKIP_LIVE_RECORDING +os.environ["PROTOCOL"] = PROTOCOL +os.environ["ACCOUNT_URL_SUFFIX"] = ACCOUNT_URL_SUFFIX FileSharePreparer = functools.partial( - EnvironmentVariableLoader, "storage", + EnvironmentVariableLoader, + "storage", storage_account_name="storagename", storage_account_key=STORAGE_ACCOUNT_FAKE_KEY, premium_storage_file_account_name="pyacrstoragestorname", @@ -57,4 +76,5 @@ def not_for_emulator(test): def skip_test_if_targeting_emulator(self): test(self) + return skip_test_if_targeting_emulator diff --git a/sdk/storage/azure-storage-file-share/tests/test_directory.py b/sdk/storage/azure-storage-file-share/tests/test_directory.py index 72ad5cc0030c..419a42afb8be 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_directory.py +++ b/sdk/storage/azure-storage-file-share/tests/test_directory.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -8,13 +9,9 @@ from datetime import datetime, timedelta, timezone import pytest - -from devtools_testutils import recorded_by_proxy -from devtools_testutils.storage import StorageRecordedTestCase -from settings.testcase import FileSharePreparer - -from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError +from azure.core.exceptions import ClientAuthenticationError, ResourceExistsError, ResourceNotFoundError from azure.storage.fileshare import ( + ContentSettings, generate_share_sas, NTFSAttributes, ShareDirectoryClient, @@ -23,11 +20,16 @@ StorageErrorCode, ) +from devtools_testutils import recorded_by_proxy +from devtools_testutils.storage import StorageRecordedTestCase +from settings.testcase import FileSharePreparer # ------------------------------------------------------------------------------ -TEST_FILE_PERMISSIONS = 'O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-' \ - '1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;' \ - 'S-1-5-21-397955417-626881126-188441444-3053964)' +TEST_FILE_PERMISSIONS = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)" +) TEST_INTENT = "backup" @@ -36,7 +38,7 @@ def _setup(self, storage_account_name, storage_account_key): url = self.account_url(storage_account_name, "file") credential = storage_account_key self.fsc = ShareServiceClient(url, credential=credential.secret) - self.share_name = self.get_resource_name('utshare') + self.share_name = self.get_resource_name("utshare") if not self.is_playback(): try: @@ -50,6 +52,7 @@ def _teardown(self, FILE_PATH): os.remove(FILE_PATH) except: pass + # --Helpers----------------------------------------------------------------- # --Test cases for directories ---------------------------------------------- @@ -63,7 +66,7 @@ def test_create_directories(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) # Act - created = share_client.create_directory('dir1') + created = share_client.create_directory("dir1") # Assert assert created @@ -76,10 +79,10 @@ def test_create_directories_with_metadata(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act - directory = share_client.create_directory('dir1', metadata=metadata) + directory = share_client.create_directory("dir1", metadata=metadata) # Assert md = directory.get_directory_properties().metadata @@ -95,9 +98,9 @@ def test_create_directories_fail_on_exist(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) # Act - created = share_client.create_directory('dir1') + created = share_client.create_directory("dir1") with pytest.raises(ResourceExistsError): - share_client.create_directory('dir1') + share_client.create_directory("dir1") # Assert assert created @@ -111,17 +114,19 @@ def test_create_directory_set_smb_properties(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory_client = share_client.get_directory_client('dir1') + directory_client = share_client.get_directory_client("dir1") file_attributes = NTFSAttributes(read_only=True, directory=True) file_creation_time = file_last_write_time = file_change_time = datetime( - 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc) + 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc + ) # Act directory_client.create_directory( file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, - file_change_time=file_change_time) + file_change_time=file_change_time, + ) directory_properties = directory_client.get_directory_properties() # Assert @@ -129,8 +134,8 @@ def test_create_directory_set_smb_properties(self, **kwargs): assert file_creation_time == directory_properties.creation_time assert file_last_write_time == directory_properties.last_write_time assert file_change_time == directory_properties.change_time - assert 'ReadOnly' in directory_properties.file_attributes - assert 'Directory' in directory_properties.file_attributes + assert "ReadOnly" in directory_properties.file_attributes + assert "Directory" in directory_properties.file_attributes @FileSharePreparer() @recorded_by_proxy @@ -143,10 +148,12 @@ def test_create_directory_with_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act created = directory_client.create_directory() @@ -162,20 +169,22 @@ def test_create_directory_with_trailing_dot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory_name = 'dir1' + directory_name = "dir1" directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, directory_name + '.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + directory_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) # Act created = directory_client.create_directory() # Assert assert created - assert directory_client.directory_path == directory_name + '.' + assert directory_client.directory_path == directory_name + "." @FileSharePreparer() @recorded_by_proxy @@ -185,14 +194,14 @@ def test_create_subdirectories(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") # Act - created = directory.create_subdirectory('dir2') + created = directory.create_subdirectory("dir2") # Assert assert created - assert created.directory_path == 'dir1/dir2' + assert created.directory_path == "dir1/dir2" @FileSharePreparer() @recorded_by_proxy @@ -202,15 +211,15 @@ def test_create_subdirectories_with_metadata(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') - metadata = {'hello': 'world', 'number': '42'} + directory = share_client.create_directory("dir1") + metadata = {"hello": "world", "number": "42"} # Act - created = directory.create_subdirectory('dir2', metadata=metadata) + created = directory.create_subdirectory("dir2", metadata=metadata) # Assert assert created - assert created.directory_path == 'dir1/dir2' + assert created.directory_path == "dir1/dir2" sub_metadata = created.get_directory_properties().metadata assert sub_metadata == metadata @@ -222,19 +231,19 @@ def test_create_subdirectory_in_root(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - share_client.create_directory('dir1') + share_client.create_directory("dir1") # Act rooted_directory = share_client.get_directory_client() - sub_dir_client = rooted_directory.get_subdirectory_client('dir2') + sub_dir_client = rooted_directory.get_subdirectory_client("dir2") sub_dir_client.create_directory() list_dir = list(share_client.list_directories_and_files()) # Assert assert len(list_dir) == 2 - assert list_dir[0]['name'] == 'dir1' - assert list_dir[1]['name'] == 'dir2' + assert list_dir[0]["name"] == "dir1" + assert list_dir[1]["name"] == "dir2" @FileSharePreparer() @recorded_by_proxy @@ -243,10 +252,10 @@ def test_create_file_in_directory(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_data = b'12345678' * 1024 - file_name = self.get_resource_name('file') + file_data = b"12345678" * 1024 + file_name = self.get_resource_name("file") share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") # Act new_file = directory.upload_file(file_name, file_data) @@ -262,9 +271,9 @@ def test_delete_file_in_directory(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_name = self.get_resource_name('file') + file_name = self.get_resource_name("file") share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") new_file = directory.upload_file(file_name, "hello world") # Act @@ -283,7 +292,7 @@ def test_share_directory_exists(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") directory2 = share_client.get_directory_client("dir2") @@ -298,15 +307,15 @@ def test_delete_subdirectories(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') - directory.create_subdirectory('dir2') + directory = share_client.create_directory("dir1") + directory.create_subdirectory("dir2") # Act - deleted = directory.delete_subdirectory('dir2') + deleted = directory.delete_subdirectory("dir2") # Assert assert deleted is None - subdir = directory.get_subdirectory_client('dir2') + subdir = directory.get_subdirectory_client("dir2") with pytest.raises(ResourceNotFoundError): subdir.get_directory_properties() @@ -318,7 +327,7 @@ def test_get_directory_properties(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") # Act props = directory.get_directory_properties() @@ -339,10 +348,12 @@ def test_get_directory_properties_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act directory_client.create_directory() @@ -362,14 +373,14 @@ def test_get_directory_properties_with_snapshot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) metadata = {"test1": "foo", "test2": "bar"} - directory = share_client.create_directory('dir1', metadata=metadata) + directory = share_client.create_directory("dir1", metadata=metadata) snapshot1 = share_client.create_snapshot() metadata2 = {"test100": "foo100", "test200": "bar200"} directory.set_directory_metadata(metadata2) # Act share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot1) - snap_dir = share_client.get_directory_client('dir1') + snap_dir = share_client.get_directory_client("dir1") props = snap_dir.get_directory_properties() # Assert @@ -387,10 +398,12 @@ def test_get_directory_properties_with_trailing_dot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) # Act directory.create_directory() @@ -410,14 +423,14 @@ def test_get_directory_metadata_with_snapshot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) metadata = {"test1": "foo", "test2": "bar"} - directory = share_client.create_directory('dir1', metadata=metadata) + directory = share_client.create_directory("dir1", metadata=metadata) snapshot1 = share_client.create_snapshot() metadata2 = {"test100": "foo100", "test200": "bar200"} directory.set_directory_metadata(metadata2) # Act share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot1) - snap_dir = share_client.get_directory_client('dir1') + snap_dir = share_client.get_directory_client("dir1") snapshot_metadata = snap_dir.get_directory_properties().metadata # Assert @@ -432,7 +445,7 @@ def test_get_directory_properties_with_non_existing_directory(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.get_directory_client('dir1') + directory = share_client.get_directory_client("dir1") # Act with pytest.raises(ResourceNotFoundError): @@ -448,7 +461,7 @@ def test_directory_exists(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") # Act exists = directory.get_directory_properties() @@ -464,7 +477,7 @@ def test_directory_not_exists(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.get_directory_client('dir1') + directory = share_client.get_directory_client("dir1") # Act with pytest.raises(ResourceNotFoundError): @@ -480,7 +493,7 @@ def test_directory_parent_not_exists(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.get_directory_client('missing1/missing2') + directory = share_client.get_directory_client("missing1/missing2") # Act with pytest.raises(ResourceNotFoundError) as e: @@ -497,13 +510,13 @@ def test_directory_exists_with_snapshot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") snapshot = share_client.create_snapshot() directory.delete_directory() # Act share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot) - snap_dir = share_client.get_directory_client('dir1') + snap_dir = share_client.get_directory_client("dir1") exists = snap_dir.get_directory_properties() # Assert @@ -518,11 +531,11 @@ def test_directory_not_exists_with_snapshot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) snapshot = share_client.create_snapshot() - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") # Act share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot) - snap_dir = share_client.get_directory_client('dir1') + snap_dir = share_client.get_directory_client("dir1") with pytest.raises(ResourceNotFoundError): snap_dir.get_directory_properties() @@ -537,8 +550,8 @@ def test_get_set_directory_metadata(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') - metadata = {'hello': 'world', 'number': '43'} + directory = share_client.create_directory("dir1") + metadata = {"hello": "world", "number": "43"} # Act directory.set_directory_metadata(metadata) @@ -557,11 +570,13 @@ def test_get_set_directory_metadata_with_oauth(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) - metadata = {'hello': 'world', 'number': '43'} + token_intent=TEST_INTENT, + ) + metadata = {"hello": "world", "number": "43"} # Act directory_client.create_directory() @@ -579,7 +594,7 @@ def test_set_directory_properties_with_empty_smb_properties(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory_client = share_client.create_directory('dir1') + directory_client = share_client.create_directory("dir1") directory_properties_on_creation = directory_client.get_directory_properties() # Act @@ -603,10 +618,12 @@ def test_set_directory_properties_with_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act directory_client.create_directory() @@ -621,10 +638,10 @@ def test_set_directory_properties_with_oauth(self, **kwargs): # Act directory_client.set_http_headers( - file_attributes='None', + file_attributes="None", file_creation_time=new_creation_time, file_last_write_time=new_last_write_time, - file_change_time=new_change_time + file_change_time=new_change_time, ) directory_properties = directory_client.get_directory_properties() @@ -642,7 +659,7 @@ def test_set_directory_properties_with_file_permission_key(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory_client = share_client.create_directory('dir1') + directory_client = share_client.create_directory("dir1") directory_properties_on_creation = directory_client.get_directory_properties() permission_key = directory_properties_on_creation.permission_key @@ -656,11 +673,12 @@ def test_set_directory_properties_with_file_permission_key(self, **kwargs): # Act directory_client.set_http_headers( - file_attributes='None', + file_attributes="None", file_creation_time=new_creation_time, file_last_write_time=new_last_write_time, file_change_time=new_change_time, - permission_key=permission_key) + permission_key=permission_key, + ) directory_properties = directory_client.get_directory_properties() # Assert @@ -678,10 +696,12 @@ def test_set_http_headers_with_trailing_dot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) directory_client.create_directory() directory_properties_on_creation = directory_client.get_directory_properties() @@ -696,11 +716,12 @@ def test_set_http_headers_with_trailing_dot(self, **kwargs): # Act directory_client.set_http_headers( - file_attributes='None', + file_attributes="None", file_creation_time=new_creation_time, file_last_write_time=new_last_write_time, file_change_time=new_change_time, - permission_key=permission_key) + permission_key=permission_key, + ) directory_properties = directory_client.get_directory_properties() # Assert @@ -717,7 +738,7 @@ def test_list_subdirectories_and_files(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") directory.create_subdirectory("subdir1") directory.create_subdirectory("subdir2") directory.create_subdirectory("subdir3") @@ -730,18 +751,18 @@ def test_list_subdirectories_and_files(self, **kwargs): # Assert assert len(list_dir) == 6 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'subdir3' - assert list_dir[2]['is_directory'] == True - assert list_dir[3]['name'] == 'file1' - assert list_dir[3]['is_directory'] == False - assert list_dir[4]['name'] == 'file2' - assert list_dir[4]['is_directory'] == False - assert list_dir[5]['name'] == 'file3' - assert list_dir[5]['is_directory'] == False + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2" + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "subdir3" + assert list_dir[2]["is_directory"] == True + assert list_dir[3]["name"] == "file1" + assert list_dir[3]["is_directory"] == False + assert list_dir[4]["name"] == "file2" + assert list_dir[4]["is_directory"] == False + assert list_dir[5]["name"] == "file3" + assert list_dir[5]["is_directory"] == False @FileSharePreparer() @recorded_by_proxy @@ -754,10 +775,12 @@ def test_list_subdirectories_and_files_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act directory_client.create_directory() @@ -773,18 +796,18 @@ def test_list_subdirectories_and_files_oauth(self, **kwargs): # Assert assert len(list_dir) == 6 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'subdir3' - assert list_dir[2]['is_directory'] == True - assert list_dir[3]['name'] == 'file1' - assert list_dir[3]['is_directory'] == False - assert list_dir[4]['name'] == 'file2' - assert list_dir[4]['is_directory'] == False - assert list_dir[5]['name'] == 'file3' - assert list_dir[5]['is_directory'] == False + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2" + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "subdir3" + assert list_dir[2]["is_directory"] == True + assert list_dir[3]["name"] == "file1" + assert list_dir[3]["is_directory"] == False + assert list_dir[4]["name"] == "file2" + assert list_dir[4]["is_directory"] == False + assert list_dir[5]["name"] == "file3" + assert list_dir[5]["is_directory"] == False @FileSharePreparer() @recorded_by_proxy @@ -795,10 +818,12 @@ def test_list_subdirectories_with_trailing_dot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) directory.create_directory() directory.create_subdirectory("subdir1.") directory.create_subdirectory("subdir2.") @@ -808,12 +833,12 @@ def test_list_subdirectories_with_trailing_dot(self, **kwargs): # Assert assert len(list_dir) == 3 - assert list_dir[0]['name'] == 'subdir1.' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2.' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'subdir3.' - assert list_dir[2]['is_directory'] == True + assert list_dir[0]["name"] == "subdir1." + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2." + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "subdir3." + assert list_dir[2]["is_directory"] == True @FileSharePreparer() @recorded_by_proxy @@ -823,7 +848,7 @@ def test_list_subdirectories_and_files_encoded(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('directory\uFFFE') + directory = share_client.create_directory("directory\uFFFE") directory.create_subdirectory("subdir1\uFFFE") directory.upload_file("file\uFFFE", "data1") @@ -832,10 +857,10 @@ def test_list_subdirectories_and_files_encoded(self, **kwargs): # Assert assert len(list_dir) == 2 - assert list_dir[0]['name'] == 'subdir1\uFFFE' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'file\uFFFE' - assert list_dir[1]['is_directory'] == False + assert list_dir[0]["name"] == "subdir1\uFFFE" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "file\uFFFE" + assert list_dir[1]["is_directory"] == False @FileSharePreparer() @recorded_by_proxy @@ -845,7 +870,7 @@ def test_list_subdirectories_and_files_encoded_prefix(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('\uFFFFdirectory') + directory = share_client.create_directory("\uFFFFdirectory") directory.create_subdirectory("\uFFFFsubdir1") directory.upload_file("\uFFFFfile", "data1") @@ -854,10 +879,10 @@ def test_list_subdirectories_and_files_encoded_prefix(self, **kwargs): # Assert assert len(list_dir) == 2 - assert list_dir[0]['name'] == '\uFFFFsubdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == '\uFFFFfile' - assert list_dir[1]['is_directory'] == False + assert list_dir[0]["name"] == "\uFFFFsubdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "\uFFFFfile" + assert list_dir[1]["is_directory"] == False @FileSharePreparer() @recorded_by_proxy @@ -867,7 +892,7 @@ def test_list_subdirectories_and_files_include_other_data(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") directory.create_subdirectory("subdir1") directory.create_subdirectory("subdir2") directory.create_subdirectory("subdir3") @@ -876,8 +901,9 @@ def test_list_subdirectories_and_files_include_other_data(self, **kwargs): directory.upload_file("file3", "data3") # Act - list_dir = list(directory.list_directories_and_files( - include=["timestamps", "Etag", "Attributes", "PermissionKey"])) + list_dir = list( + directory.list_directories_and_files(include=["timestamps", "Etag", "Attributes", "PermissionKey"]) + ) assert len(list_dir) == 6 assert list_dir[0].etag is not None @@ -900,7 +926,7 @@ def test_list_subdirectories_and_files_include_extended_info(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") directory.create_subdirectory("subdir1") list_dir = list(directory.list_directories_and_files(include_extended_info=True)) @@ -917,7 +943,7 @@ def test_list_subdirectories_and_files_with_prefix(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") directory.create_subdirectory("subdir1") directory.create_subdirectory("subdir2") directory.create_subdirectory("subdir3") @@ -930,12 +956,12 @@ def test_list_subdirectories_and_files_with_prefix(self, **kwargs): # Assert assert len(list_dir) == 3 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'subdir3' - assert list_dir[2]['is_directory'] == True + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2" + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "subdir3" + assert list_dir[2]["is_directory"] == True @FileSharePreparer() @recorded_by_proxy @@ -945,7 +971,7 @@ def test_list_subdirectories_and_files_with_snapshot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") directory.create_subdirectory("subdir1") directory.create_subdirectory("subdir2") directory.upload_file("file1", "data1") @@ -956,20 +982,20 @@ def test_list_subdirectories_and_files_with_snapshot(self, **kwargs): directory.upload_file("file3", "data3") share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot) - snapshot_dir = share_client.get_directory_client('dir1') + snapshot_dir = share_client.get_directory_client("dir1") # Act list_dir = list(snapshot_dir.list_directories_and_files()) # Assert assert len(list_dir) == 3 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'file1' - assert list_dir[2]['is_directory'] == False - assert list_dir[2]['size'] == 5 + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2" + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "file1" + assert list_dir[2]["is_directory"] == False + assert list_dir[2]["size"] == 5 @FileSharePreparer() @recorded_by_proxy @@ -979,7 +1005,7 @@ def test_list_nested_subdirectories_and_files(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") subdir = directory.create_subdirectory("subdir1") subdir.create_subdirectory("subdir2") subdir.create_subdirectory("subdir3") @@ -992,11 +1018,11 @@ def test_list_nested_subdirectories_and_files(self, **kwargs): # Assert assert len(list_dir) == 2 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'file1' - assert list_dir[1]['is_directory'] == False - assert list_dir[1]['size'] == 5 + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "file1" + assert list_dir[1]["is_directory"] == False + assert list_dir[1]["size"] == 5 @FileSharePreparer() @recorded_by_proxy @@ -1013,11 +1039,11 @@ def test_list_pagination_name_starts_with(self, **kwargs): directory.upload_file(f"{prefix}{i}", "data1") directory.upload_file(f"not_{i}", "data2") - list_all = list(share_client.list_directories_and_files( - directory_name=directory_name, - name_starts_with=prefix, - results_per_page=2 - )) + list_all = list( + share_client.list_directories_and_files( + directory_name=directory_name, name_starts_with=prefix, results_per_page=2 + ) + ) assert len(list_all) == 6 for i in range(6): assert list_all[i]["name"] == f"{prefix}{i}" @@ -1030,7 +1056,7 @@ def test_delete_directory_with_existing_share(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") # Act deleted = directory.delete_directory() @@ -1051,10 +1077,12 @@ def test_delete_directory_with_existing_share_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act created = directory_client.create_directory() @@ -1075,10 +1103,12 @@ def test_delete_directory_with_trailing_dot(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) # Act directory.create_directory() @@ -1097,7 +1127,7 @@ def test_delete_directory_with_non_existing_directory(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.get_directory_client('dir1') + directory = share_client.get_directory_client("dir1") # Act with pytest.raises(ResourceNotFoundError): @@ -1113,7 +1143,7 @@ def test_get_directory_properties_server_encryption(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1') + directory = share_client.create_directory("dir1") # Act props = directory.get_directory_properties() @@ -1133,10 +1163,10 @@ def test_rename_directory(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = share_client.create_directory('dir1') + source_directory = share_client.create_directory("dir1") # Act - new_directory = source_directory.rename_directory('dir2') + new_directory = source_directory.rename_directory("dir2") # Assert props = new_directory.get_directory_properties() @@ -1153,14 +1183,16 @@ def test_rename_directory_with_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act directory_client.create_directory() - new_directory = directory_client.rename_directory('dir2') + new_directory = directory_client.rename_directory("dir2") # Assert props = new_directory.get_directory_properties() @@ -1175,13 +1207,13 @@ def test_rename_directory_different_directory(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - parent_source_directory = share_client.create_directory('dir1') - source_directory = parent_source_directory.create_subdirectory('sub1') + parent_source_directory = share_client.create_directory("dir1") + source_directory = parent_source_directory.create_subdirectory("sub1") - dest_parent_directory = share_client.create_directory('dir2') + dest_parent_directory = share_client.create_directory("dir2") # Act - new_directory_path = dest_parent_directory.directory_path + '/sub2' + new_directory_path = dest_parent_directory.directory_path + "/sub2" new_directory = source_directory.rename_directory(new_directory_path) # Assert @@ -1197,17 +1229,17 @@ def test_rename_directory_ignore_readonly(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = share_client.create_directory('dir1') - dest_directory = share_client.create_directory('dir2') - dest_file = dest_directory.get_file_client('test') + source_directory = share_client.create_directory("dir1") + dest_directory = share_client.create_directory("dir2") + dest_file = dest_directory.get_file_client("test") file_attributes = NTFSAttributes(read_only=True) dest_file.create_file(1024, file_attributes=file_attributes) # Act new_directory = source_directory.rename_directory( - dest_directory.directory_path + '/' + dest_file.file_name, - overwrite=True, ignore_read_only=True) + dest_directory.directory_path + "/" + dest_file.file_name, overwrite=True, ignore_read_only=True + ) # Assert props = new_directory.get_directory_properties() @@ -1224,10 +1256,10 @@ def test_rename_directory_file_permission(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) file_permission_key = share_client.create_permission_for_share(TEST_FILE_PERMISSIONS) - source_directory = share_client.create_directory('dir1') + source_directory = share_client.create_directory("dir1") # Act - new_directory = source_directory.rename_directory('dir2', file_permission=TEST_FILE_PERMISSIONS) + new_directory = source_directory.rename_directory("dir2", file_permission=TEST_FILE_PERMISSIONS) # Assert props = new_directory.get_directory_properties() @@ -1243,12 +1275,12 @@ def test_rename_directory_preserve_permission(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = share_client.create_directory('dir1', file_permission=TEST_FILE_PERMISSIONS) + source_directory = share_client.create_directory("dir1", file_permission=TEST_FILE_PERMISSIONS) source_props = source_directory.get_directory_properties() source_permission_key = source_props.permission_key # Act - new_directory = source_directory.rename_directory('dir2', file_permission='preserve') + new_directory = source_directory.rename_directory("dir2", file_permission="preserve") # Assert props = new_directory.get_directory_properties() @@ -1264,7 +1296,7 @@ def test_rename_directory_smb_properties(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = share_client.create_directory('dir1') + source_directory = share_client.create_directory("dir1") file_attributes = NTFSAttributes(read_only=True, directory=True) file_creation_time = datetime(2022, 1, 26, 10, 9, 30, 500000, tzinfo=timezone.utc) @@ -1273,17 +1305,18 @@ def test_rename_directory_smb_properties(self, **kwargs): # Act new_directory = source_directory.rename_directory( - 'dir2', + "dir2", file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, - file_change_time=file_change_time) + file_change_time=file_change_time, + ) # Assert props = new_directory.get_directory_properties() assert props is not None assert props.is_directory - assert str(file_attributes).replace(' ', '') == props.file_attributes.replace(' ', '') + assert str(file_attributes), props.file_attributes.replace(" " == "") assert file_creation_time == props.creation_time assert file_last_write_time == props.last_write_time assert file_change_time == props.change_time @@ -1297,15 +1330,15 @@ def test_rename_directory_dest_lease(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = share_client.create_directory('dir1') - dest_directory = share_client.create_directory('dir2') - dest_file = dest_directory.upload_file('test', b'Hello World') - lease = dest_file.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + source_directory = share_client.create_directory("dir1") + dest_directory = share_client.create_directory("dir2") + dest_file = dest_directory.upload_file("test", b"Hello World") + lease = dest_file.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act new_directory = source_directory.rename_directory( - dest_directory.directory_path + '/' + dest_file.file_name, - overwrite=True, destination_lease=lease) + dest_directory.directory_path + "/" + dest_file.file_name, overwrite=True, destination_lease=lease + ) # Assert props = new_directory.get_directory_properties() @@ -1327,16 +1360,16 @@ def test_rename_directory_share_sas(self, **kwargs): share_client.share_name, share_client.credential.account_key, expiry=datetime.utcnow() + timedelta(hours=1), - permission=ShareSasPermissions(read=True, write=True)) + permission=ShareSasPermissions(read=True, write=True), + ) source_directory = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', - credential=token) + self.account_url(storage_account_name, "file"), share_client.share_name, "dir1", credential=token + ) source_directory.create_directory() # Act - new_directory = source_directory.rename_directory('dir2' + '?' + token) + new_directory = source_directory.rename_directory("dir2" + "?" + token) # Assert props = new_directory.get_directory_properties() @@ -1350,14 +1383,16 @@ def test_rename_directory_trailing_dot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - dest_dir_name = 'dir2' + '.' + dest_dir_name = "dir2" + "." directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, allow_trailing_dot=True, - allow_source_trailing_dot=True) + allow_source_trailing_dot=True, + ) # Act directory_client.create_directory() @@ -1376,20 +1411,22 @@ def test_storage_account_audience_directory_client(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', - credential=storage_account_key.secret + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", + credential=storage_account_key.secret, ) directory_client.exists() # Act token_credential = self.get_credential(ShareServiceClient) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=token_credential, token_intent=TEST_INTENT, - audience=f'https://{storage_account_name}.file.core.windows.net' + audience=f"https://{storage_account_name}.file.core.windows.net", ) # Assert @@ -1406,20 +1443,22 @@ def test_bad_audience_directory_client(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', - credential=storage_account_key.secret + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", + credential=storage_account_key.secret, ) directory_client.exists() # Act token_credential = self.get_credential(ShareServiceClient) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=token_credential, token_intent=TEST_INTENT, - audience='https://badaudience.file.core.windows.net' + audience=f"https://badaudience.file.core.windows.net", ) # Assert @@ -1433,50 +1472,45 @@ def test_file_permission_format_directory(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - user_given_permission_sddl = ("O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" - "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" - "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL") - user_given_permission_binary = ("AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" - "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" - "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=") + user_given_permission_sddl = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL" + ) + user_given_permission_binary = ( + "AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" + "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" + "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=" + ) directory_client = share_client.create_directory( - 'dir1', - file_permission=user_given_permission_binary, - file_permission_format="binary" + "dir1", file_permission=user_given_permission_binary, file_permission_format="binary" ) props = directory_client.get_directory_properties() assert props is not None assert props.permission_key is not None - directory_client.set_http_headers( - file_permission=user_given_permission_binary, - file_permission_format="binary" - ) + directory_client.set_http_headers(file_permission=user_given_permission_binary, file_permission_format="binary") props = directory_client.get_directory_properties() assert props is not None assert props.permission_key is not None server_returned_permission = share_client.get_permission_for_share( - props.permission_key, - file_permission_format="sddl" + props.permission_key, file_permission_format="sddl" ) assert server_returned_permission == user_given_permission_sddl new_directory_client = directory_client.rename_directory( - 'dir2', - file_permission=user_given_permission_binary, - file_permission_format="binary" + "dir2", file_permission=user_given_permission_binary, file_permission_format="binary" ) props = new_directory_client.get_directory_properties() assert props is not None assert props.permission_key is not None server_returned_permission = share_client.get_permission_for_share( - props.permission_key, - file_permission_format="binary" + props.permission_key, file_permission_format="binary" ) assert server_returned_permission == user_given_permission_binary @@ -1491,20 +1525,21 @@ def test_create_directory_semantics(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.create_directory('dir1', file_property_semantics=None) + directory = share_client.create_directory("dir1", file_property_semantics=None) props = directory.get_directory_properties() assert props is not None - directory = share_client.create_directory('dir2', file_property_semantics='New') + directory = share_client.create_directory("dir2", file_property_semantics="New") props = directory.get_directory_properties() assert props is not None directory = share_client.create_directory( - 'dir3', file_property_semantics='Restore', file_permission=TEST_FILE_PERMISSIONS + "dir3", file_property_semantics="Restore", file_permission=TEST_FILE_PERMISSIONS ) props = directory.get_directory_properties() assert props is not None + # ------------------------------------------------------------------------------ -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/sdk/storage/azure-storage-file-share/tests/test_directory_async.py b/sdk/storage/azure-storage-file-share/tests/test_directory_async.py index 70397a88c842..adadd95b261e 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_directory_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_directory_async.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding: utf-8 # ------------------------------------------------------------------------- @@ -7,28 +8,24 @@ # -------------------------------------------------------------------------- import asyncio import os +import unittest from datetime import datetime, timedelta, timezone import pytest +from azure.core.exceptions import ClientAuthenticationError, ResourceExistsError, ResourceNotFoundError +from azure.storage.fileshare import generate_share_sas, NTFSAttributes, ShareSasPermissions, StorageErrorCode +from azure.storage.fileshare.aio import ShareDirectoryClient, ShareServiceClient from devtools_testutils.aio import recorded_by_proxy_async from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase from settings.testcase import FileSharePreparer -from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError -from azure.storage.fileshare import ( - generate_share_sas, - NTFSAttributes, - ShareSasPermissions, - StorageErrorCode, -) -from azure.storage.fileshare.aio import ShareDirectoryClient, ShareServiceClient - - # ------------------------------------------------------------------------------ -TEST_FILE_PERMISSIONS = 'O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-' \ - '1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;' \ - 'S-1-5-21-397955417-626881126-188441444-3053964)' +TEST_FILE_PERMISSIONS = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)" +) TEST_INTENT = "backup" @@ -38,7 +35,7 @@ async def _setup(self, storage_account_name, storage_account_key): url = self.account_url(storage_account_name, "file") credential = storage_account_key self.fsc = ShareServiceClient(url, credential=credential.secret) - self.share_name = self.get_resource_name('utshare') + self.share_name = self.get_resource_name("utshare") if not self.is_playback(): try: await self.fsc.create_share(self.share_name) @@ -64,7 +61,7 @@ async def test_create_directories(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) # Act - created = await share_client.create_directory('dir1') + created = await share_client.create_directory("dir1") # Assert assert created @@ -78,10 +75,10 @@ async def test_create_directories_with_metadata(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act - directory = await share_client.create_directory('dir1', metadata=metadata) + directory = await share_client.create_directory("dir1", metadata=metadata) # Assert props = await directory.get_directory_properties() @@ -98,9 +95,9 @@ async def test_create_directories_fail_on_exist(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) # Act - created = await share_client.create_directory('dir1') + created = await share_client.create_directory("dir1") with pytest.raises(ResourceExistsError): - await share_client.create_directory('dir1') + await share_client.create_directory("dir1") # Assert assert created @@ -115,17 +112,19 @@ async def test_create_directory_set_smb_properties(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory_client = share_client.get_directory_client('dir1') + directory_client = share_client.get_directory_client("dir1") file_attributes = NTFSAttributes(read_only=True, directory=True) - file_creation_time = file_last_write_time = file_change_time = ( - datetime(2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc)) + file_creation_time = file_last_write_time = file_change_time = datetime( + 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc + ) # Act await directory_client.create_directory( file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, - file_change_time=file_change_time) + file_change_time=file_change_time, + ) directory_properties = await directory_client.get_directory_properties() # Assert @@ -133,8 +132,8 @@ async def test_create_directory_set_smb_properties(self, **kwargs): assert file_creation_time == directory_properties.creation_time assert file_last_write_time == directory_properties.last_write_time assert file_change_time == directory_properties.change_time - assert 'ReadOnly' in directory_properties.file_attributes - assert 'Directory' in directory_properties.file_attributes + assert "ReadOnly" in directory_properties.file_attributes + assert "Directory" in directory_properties.file_attributes @FileSharePreparer() @recorded_by_proxy_async @@ -148,10 +147,12 @@ async def test_create_directory_with_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act created = await directory_client.create_directory() @@ -168,20 +169,22 @@ async def test_create_directory_with_trailing_dot(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory_name = 'dir1' + directory_name = "dir1" directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, directory_name + '.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + directory_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) # Act created = await directory_client.create_directory() # Assert assert created - assert directory_client.directory_path == directory_name + '.' + assert directory_client.directory_path == directory_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -192,15 +195,14 @@ async def test_create_subdirectories(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") # Act - created = await directory.create_subdirectory('dir2') + created = await directory.create_subdirectory("dir2") # Assert assert created - assert created.directory_path == 'dir1/dir2' - + assert created.directory_path == "dir1/dir2" @FileSharePreparer() @recorded_by_proxy_async @@ -211,15 +213,15 @@ async def test_create_subdirectories_with_metadata(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') - metadata = {'hello': 'world', 'number': '42'} + directory = await share_client.create_directory("dir1") + metadata = {"hello": "world", "number": "42"} # Act - created = await directory.create_subdirectory('dir2', metadata=metadata) + created = await directory.create_subdirectory("dir2", metadata=metadata) # Assert assert created - assert created.directory_path == 'dir1/dir2' + assert created.directory_path == "dir1/dir2" properties = await created.get_directory_properties() assert properties.metadata == metadata @@ -231,11 +233,11 @@ async def test_create_subdirectory_in_root(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - await share_client.create_directory('dir1') + await share_client.create_directory("dir1") # Act rooted_directory = share_client.get_directory_client() - sub_dir_client = rooted_directory.get_subdirectory_client('dir2') + sub_dir_client = rooted_directory.get_subdirectory_client("dir2") await sub_dir_client.create_directory() list_dir = [] @@ -244,8 +246,8 @@ async def test_create_subdirectory_in_root(self, **kwargs): # Assert assert len(list_dir) == 2 - assert list_dir[0]['name'] == 'dir1' - assert list_dir[1]['name'] == 'dir2' + assert list_dir[0]["name"] == "dir1" + assert list_dir[1]["name"] == "dir2" @FileSharePreparer() @recorded_by_proxy_async @@ -255,10 +257,10 @@ async def test_create_file_in_directory(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - file_data = b'12345678' * 1024 - file_name = self.get_resource_name('file') + file_data = b"12345678" * 1024 + file_name = self.get_resource_name("file") share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") # Act new_file = await directory.upload_file(file_name, file_data) @@ -276,9 +278,9 @@ async def test_delete_file_in_directory(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - file_name = self.get_resource_name('file') + file_name = self.get_resource_name("file") share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") new_file = await directory.upload_file(file_name, "hello world") # Act @@ -298,15 +300,15 @@ async def test_delete_subdirectories(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') - await directory.create_subdirectory('dir2') + directory = await share_client.create_directory("dir1") + await directory.create_subdirectory("dir2") # Act - deleted = await directory.delete_subdirectory('dir2') + deleted = await directory.delete_subdirectory("dir2") # Assert assert deleted is None - subdir = directory.get_subdirectory_client('dir2') + subdir = directory.get_subdirectory_client("dir2") with pytest.raises(ResourceNotFoundError): await subdir.get_directory_properties() @@ -319,7 +321,7 @@ async def test_get_directory_properties(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") # Act props = await directory.get_directory_properties() @@ -341,10 +343,12 @@ async def test_get_directory_properties_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act await directory_client.create_directory() @@ -365,14 +369,14 @@ async def test_get_directory_properties_with_snapshot(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) metadata = {"test1": "foo", "test2": "bar"} - directory = await share_client.create_directory('dir1', metadata=metadata) + directory = await share_client.create_directory("dir1", metadata=metadata) snapshot1 = await share_client.create_snapshot() metadata2 = {"test100": "foo100", "test200": "bar200"} await directory.set_directory_metadata(metadata2) # Act share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot1) - snap_dir = share_client.get_directory_client('dir1') + snap_dir = share_client.get_directory_client("dir1") props = await snap_dir.get_directory_properties() # Assert @@ -391,10 +395,12 @@ async def test_get_directory_properties_with_trailing_dot(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) # Act await directory.create_directory() @@ -415,14 +421,14 @@ async def test_get_directory_metadata_with_snapshot(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) metadata = {"test1": "foo", "test2": "bar"} - directory = await share_client.create_directory('dir1', metadata=metadata) + directory = await share_client.create_directory("dir1", metadata=metadata) snapshot1 = await share_client.create_snapshot() metadata2 = {"test100": "foo100", "test200": "bar200"} await directory.set_directory_metadata(metadata2) # Act share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot1) - snap_dir = share_client.get_directory_client('dir1') + snap_dir = share_client.get_directory_client("dir1") snapshot_props = await snap_dir.get_directory_properties() # Assert @@ -438,7 +444,7 @@ async def test_get_directory_properties_with_non_existing_directory(self, **kwar # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.get_directory_client('dir1') + directory = share_client.get_directory_client("dir1") # Act with pytest.raises(ResourceNotFoundError): @@ -454,7 +460,7 @@ async def test_share_directory_exists(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") directory2 = share_client.get_directory_client("dir2") @@ -472,7 +478,7 @@ async def test_directory_exists(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") # Act exists = await directory.get_directory_properties() @@ -489,7 +495,7 @@ async def test_directory_not_exists(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.get_directory_client('dir1') + directory = share_client.get_directory_client("dir1") # Act with pytest.raises(ResourceNotFoundError): @@ -506,7 +512,7 @@ async def test_directory_parent_not_exists(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.get_directory_client('missing1/missing2') + directory = share_client.get_directory_client("missing1/missing2") # Act with pytest.raises(ResourceNotFoundError) as e: @@ -524,13 +530,13 @@ async def test_directory_exists_with_snapshot(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") snapshot = await share_client.create_snapshot() await directory.delete_directory() # Act share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot) - snap_dir = share_client.get_directory_client('dir1') + snap_dir = share_client.get_directory_client("dir1") exists = await snap_dir.get_directory_properties() # Assert @@ -546,11 +552,11 @@ async def test_directory_not_exists_with_snapshot(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) snapshot = await share_client.create_snapshot() - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") # Act share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot) - snap_dir = share_client.get_directory_client('dir1') + snap_dir = share_client.get_directory_client("dir1") with pytest.raises(ResourceNotFoundError): await snap_dir.get_directory_properties() @@ -566,8 +572,8 @@ async def test_get_set_directory_metadata(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') - metadata = {'hello': 'world', 'number': '43'} + directory = await share_client.create_directory("dir1") + metadata = {"hello": "world", "number": "43"} # Act await directory.set_directory_metadata(metadata) @@ -587,11 +593,13 @@ async def test_get_set_directory_metadata_with_oauth(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) - metadata = {'hello': 'world', 'number': '43'} + token_intent=TEST_INTENT, + ) + metadata = {"hello": "world", "number": "43"} # Act await directory_client.create_directory() @@ -610,7 +618,7 @@ async def test_set_directory_properties_with_empty_smb_properties(self, **kwargs # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory_client = await share_client.create_directory('dir1') + directory_client = await share_client.create_directory("dir1") directory_properties_on_creation = await directory_client.get_directory_properties() # Act @@ -634,10 +642,12 @@ async def test_set_directory_properties_with_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act await directory_client.create_directory() @@ -652,10 +662,10 @@ async def test_set_directory_properties_with_oauth(self, **kwargs): # Act await directory_client.set_http_headers( - file_attributes='None', + file_attributes="None", file_creation_time=new_creation_time, file_last_write_time=new_last_write_time, - file_change_time=new_change_time + file_change_time=new_change_time, ) directory_properties = await directory_client.get_directory_properties() @@ -674,7 +684,7 @@ async def test_set_directory_properties_with_file_permission_key(self, **kwargs) # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory_client = await share_client.create_directory('dir1') + directory_client = await share_client.create_directory("dir1") directory_properties_on_creation = await directory_client.get_directory_properties() permission_key = directory_properties_on_creation.permission_key @@ -688,11 +698,12 @@ async def test_set_directory_properties_with_file_permission_key(self, **kwargs) # Act await directory_client.set_http_headers( - file_attributes='None', + file_attributes="None", file_creation_time=new_creation_time, file_last_write_time=new_last_write_time, file_change_time=new_change_time, - permission_key=permission_key) + permission_key=permission_key, + ) directory_properties = await directory_client.get_directory_properties() # Assert @@ -710,10 +721,12 @@ async def test_set_http_headers_with_trailing_dot(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await directory_client.create_directory() directory_properties_on_creation = await directory_client.get_directory_properties() @@ -728,11 +741,12 @@ async def test_set_http_headers_with_trailing_dot(self, **kwargs): # Act await directory_client.set_http_headers( - file_attributes='None', + file_attributes="None", file_creation_time=new_creation_time, file_last_write_time=new_last_write_time, file_change_time=new_change_time, - permission_key=permission_key) + permission_key=permission_key, + ) directory_properties = await directory_client.get_directory_properties() # Assert @@ -749,14 +763,15 @@ async def test_list_subdirectories_and_files(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") await asyncio.gather( directory.create_subdirectory("subdir1"), directory.create_subdirectory("subdir2"), directory.create_subdirectory("subdir3"), directory.upload_file("file1", "data1"), directory.upload_file("file2", "data2"), - directory.upload_file("file3", "data3")) + directory.upload_file("file3", "data3"), + ) # Act list_dir = [] @@ -766,21 +781,21 @@ async def test_list_subdirectories_and_files(self, **kwargs): # Assert assert len(list_dir) == 6 assert len(list_dir) == 6 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'subdir3' - assert list_dir[2]['is_directory'] == True - assert list_dir[3]['name'] == 'file1' - assert list_dir[3]['is_directory'] == False - assert list_dir[3]['size'] == 5 - assert list_dir[4]['name'] == 'file2' - assert list_dir[4]['is_directory'] == False - assert list_dir[4]['size'] == 5 - assert list_dir[5]['name'] == 'file3' - assert list_dir[5]['is_directory'] == False - assert list_dir[5]['size'] == 5 + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2" + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "subdir3" + assert list_dir[2]["is_directory"] == True + assert list_dir[3]["name"] == "file1" + assert list_dir[3]["is_directory"] == False + assert list_dir[3]["size"] == 5 + assert list_dir[4]["name"] == "file2" + assert list_dir[4]["is_directory"] == False + assert list_dir[4]["size"] == 5 + assert list_dir[5]["name"] == "file3" + assert list_dir[5]["is_directory"] == False + assert list_dir[5]["size"] == 5 @FileSharePreparer() @recorded_by_proxy_async @@ -794,10 +809,12 @@ async def test_list_subdirectories_and_files_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act await directory_client.create_directory() @@ -807,7 +824,8 @@ async def test_list_subdirectories_and_files_oauth(self, **kwargs): directory_client.create_subdirectory("subdir3"), directory_client.upload_file("file1", "data1"), directory_client.upload_file("file2", "data2"), - directory_client.upload_file("file3", "data3")) + directory_client.upload_file("file3", "data3"), + ) # Act list_dir = [] @@ -817,21 +835,21 @@ async def test_list_subdirectories_and_files_oauth(self, **kwargs): # Assert assert len(list_dir) == 6 assert len(list_dir) == 6 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'subdir3' - assert list_dir[2]['is_directory'] == True - assert list_dir[3]['name'] == 'file1' - assert list_dir[3]['is_directory'] == False - assert list_dir[3]['size'] == 5 - assert list_dir[4]['name'] == 'file2' - assert list_dir[4]['is_directory'] == False - assert list_dir[4]['size'] == 5 - assert list_dir[5]['name'] == 'file3' - assert list_dir[5]['is_directory'] == False - assert list_dir[5]['size'] == 5 + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2" + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "subdir3" + assert list_dir[2]["is_directory"] == True + assert list_dir[3]["name"] == "file1" + assert list_dir[3]["is_directory"] == False + assert list_dir[3]["size"] == 5 + assert list_dir[4]["name"] == "file2" + assert list_dir[4]["is_directory"] == False + assert list_dir[4]["size"] == 5 + assert list_dir[5]["name"] == "file3" + assert list_dir[5]["is_directory"] == False + assert list_dir[5]["size"] == 5 @FileSharePreparer() @recorded_by_proxy_async @@ -843,15 +861,17 @@ async def test_list_subdirectories_with_trailing_dot(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await directory.create_directory() await asyncio.gather( directory.create_subdirectory("subdir1."), directory.create_subdirectory("subdir2."), - directory.create_subdirectory("subdir3.") + directory.create_subdirectory("subdir3."), ) # Act @@ -861,12 +881,12 @@ async def test_list_subdirectories_with_trailing_dot(self, **kwargs): # Assert assert len(list_dir) == 3 - assert list_dir[0]['name'] == 'subdir1.' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2.' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'subdir3.' - assert list_dir[2]['is_directory'] == True + assert list_dir[0]["name"] == "subdir1." + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2." + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "subdir3." + assert list_dir[2]["is_directory"] == True @FileSharePreparer() @recorded_by_proxy_async @@ -877,10 +897,10 @@ async def test_list_subdirectories_and_files_encoded_async(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1\uFFFE') + directory = await share_client.create_directory("dir1\uFFFE") await asyncio.gather( - directory.create_subdirectory("subdir1\uFFFE"), - directory.upload_file("file1\uFFFE", "data1")) + directory.create_subdirectory("subdir1\uFFFE"), directory.upload_file("file1\uFFFE", "data1") + ) # Act list_dir = [] @@ -889,10 +909,10 @@ async def test_list_subdirectories_and_files_encoded_async(self, **kwargs): # Assert assert len(list_dir) == 2 - assert list_dir[0]['name'] == 'subdir1\uFFFE' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'file1\uFFFE' - assert list_dir[1]['is_directory'] == False + assert list_dir[0]["name"] == "subdir1\uFFFE" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "file1\uFFFE" + assert list_dir[1]["is_directory"] == False @FileSharePreparer() @recorded_by_proxy_async @@ -903,10 +923,10 @@ async def test_list_subdirectories_and_files_encoded_prefix_async(self, **kwargs # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('\uFFFFdir1') + directory = await share_client.create_directory("\uFFFFdir1") await asyncio.gather( - directory.create_subdirectory("\uFFFFsubdir1"), - directory.upload_file("\uFFFFfile1", "data1")) + directory.create_subdirectory("\uFFFFsubdir1"), directory.upload_file("\uFFFFfile1", "data1") + ) # Act list_dir = [] @@ -915,10 +935,10 @@ async def test_list_subdirectories_and_files_encoded_prefix_async(self, **kwargs # Assert assert len(list_dir) == 2 - assert list_dir[0]['name'] == '\uFFFFsubdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == '\uFFFFfile1' - assert list_dir[1]['is_directory'] == False + assert list_dir[0]["name"] == "\uFFFFsubdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "\uFFFFfile1" + assert list_dir[1]["is_directory"] == False @FileSharePreparer() @recorded_by_proxy_async @@ -929,14 +949,15 @@ async def test_list_subdirectories_and_files_include_other_data_async(self, **kw # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") await asyncio.gather( directory.create_subdirectory("subdir1"), directory.create_subdirectory("subdir2"), directory.create_subdirectory("subdir3"), directory.upload_file("file1", "data1"), directory.upload_file("file2", "data2"), - directory.upload_file("file3", "data3")) + directory.upload_file("file3", "data3"), + ) # Act list_dir = [] @@ -968,9 +989,8 @@ async def test_list_subdirectories_and_files_include_extended_info(self, **kwarg # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') - await asyncio.gather( - directory.create_subdirectory("subdir1")) + directory = await share_client.create_directory("dir1") + await asyncio.gather(directory.create_subdirectory("subdir1")) # Act list_dir = [] @@ -991,14 +1011,15 @@ async def test_list_subdirectories_and_files_with_prefix(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") await asyncio.gather( directory.create_subdirectory("subdir1"), directory.create_subdirectory("subdir2"), directory.create_subdirectory("subdir3"), directory.upload_file("file1", "data1"), directory.upload_file("file2", "data2"), - directory.upload_file("file3", "data3")) + directory.upload_file("file3", "data3"), + ) # Act list_dir = [] @@ -1007,12 +1028,12 @@ async def test_list_subdirectories_and_files_with_prefix(self, **kwargs): # Assert assert len(list_dir) == 3 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'subdir3' - assert list_dir[2]['is_directory'] == True + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2" + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "subdir3" + assert list_dir[2]["is_directory"] == True @FileSharePreparer() @recorded_by_proxy_async @@ -1023,20 +1044,22 @@ async def test_list_subdirectories_and_files_with_snapshot(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") await asyncio.gather( directory.create_subdirectory("subdir1"), directory.create_subdirectory("subdir2"), - directory.upload_file("file1", "data1")) + directory.upload_file("file1", "data1"), + ) snapshot = await share_client.create_snapshot() await asyncio.gather( directory.create_subdirectory("subdir3"), directory.upload_file("file2", "data2"), - directory.upload_file("file3", "data3")) + directory.upload_file("file3", "data3"), + ) share_client = self.fsc.get_share_client(self.share_name, snapshot=snapshot) - snapshot_dir = share_client.get_directory_client('dir1') + snapshot_dir = share_client.get_directory_client("dir1") # Act list_dir = [] @@ -1045,13 +1068,13 @@ async def test_list_subdirectories_and_files_with_snapshot(self, **kwargs): # Assert assert len(list_dir) == 3 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'subdir2' - assert list_dir[1]['is_directory'] == True - assert list_dir[2]['name'] == 'file1' - assert list_dir[2]['is_directory'] == False - assert list_dir[2]['size'] == 5 + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "subdir2" + assert list_dir[1]["is_directory"] == True + assert list_dir[2]["name"] == "file1" + assert list_dir[2]["is_directory"] == False + assert list_dir[2]["size"] == 5 @FileSharePreparer() @recorded_by_proxy_async @@ -1062,14 +1085,15 @@ async def test_list_nested_subdirectories_and_files(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") subdir = await directory.create_subdirectory("subdir1") await subdir.create_subdirectory("subdir2") await subdir.create_subdirectory("subdir3") await asyncio.gather( directory.upload_file("file1", "data1"), subdir.upload_file("file2", "data2"), - subdir.upload_file("file3", "data3")) + subdir.upload_file("file3", "data3"), + ) # Act list_dir = [] @@ -1078,11 +1102,11 @@ async def test_list_nested_subdirectories_and_files(self, **kwargs): # Assert assert len(list_dir) == 2 - assert list_dir[0]['name'] == 'subdir1' - assert list_dir[0]['is_directory'] == True - assert list_dir[1]['name'] == 'file1' - assert list_dir[1]['is_directory'] == False - assert list_dir[1]['size'] == 5 + assert list_dir[0]["name"] == "subdir1" + assert list_dir[0]["is_directory"] == True + assert list_dir[1]["name"] == "file1" + assert list_dir[1]["is_directory"] == False + assert list_dir[1]["size"] == 5 @FileSharePreparer() @recorded_by_proxy_async @@ -1101,9 +1125,7 @@ async def test_list_pagination_name_starts_with(self, **kwargs): list_all = [] async for path in share_client.list_directories_and_files( - directory_name=directory_name, - name_starts_with=prefix, - results_per_page=2 + directory_name=directory_name, name_starts_with=prefix, results_per_page=2 ): list_all.append(path) assert len(list_all) == 6 @@ -1119,7 +1141,7 @@ async def test_delete_directory_with_existing_share(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") # Act deleted = await directory.delete_directory() @@ -1141,10 +1163,12 @@ async def test_delete_directory_with_existing_share_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act await directory_client.create_directory() @@ -1166,10 +1190,12 @@ async def test_delete_directory_with_trailing_dot(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) # Act await directory.create_directory() @@ -1189,7 +1215,7 @@ async def test_delete_directory_with_non_existing_directory(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = share_client.get_directory_client('dir1') + directory = share_client.get_directory_client("dir1") # Act with pytest.raises(ResourceNotFoundError): @@ -1206,7 +1232,7 @@ async def test_get_directory_properties_server_encryption(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1') + directory = await share_client.create_directory("dir1") # Act props = await directory.get_directory_properties() @@ -1227,10 +1253,10 @@ async def test_rename_directory(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = await share_client.create_directory('dir1') + source_directory = await share_client.create_directory("dir1") # Act - new_directory = await source_directory.rename_directory('dir2') + new_directory = await source_directory.rename_directory("dir2") # Assert props = await new_directory.get_directory_properties() @@ -1248,14 +1274,16 @@ async def test_rename_directory_with_oauth(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act await directory_client.create_directory() - new_directory = await directory_client.rename_directory('dir2') + new_directory = await directory_client.rename_directory("dir2") # Assert props = await new_directory.get_directory_properties() @@ -1271,13 +1299,13 @@ async def test_rename_directory_different_directory(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - parent_source_directory = await share_client.create_directory('dir1') - source_directory = await parent_source_directory.create_subdirectory('sub1') + parent_source_directory = await share_client.create_directory("dir1") + source_directory = await parent_source_directory.create_subdirectory("sub1") - dest_parent_directory = await share_client.create_directory('dir2') + dest_parent_directory = await share_client.create_directory("dir2") # Act - new_directory_path = dest_parent_directory.directory_path + '/sub2' + new_directory_path = dest_parent_directory.directory_path + "/sub2" new_directory = await source_directory.rename_directory(new_directory_path) # Assert @@ -1294,17 +1322,17 @@ async def test_rename_directory_ignore_readonly(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = await share_client.create_directory('dir1') - dest_directory = await share_client.create_directory('dir2') - dest_file = dest_directory.get_file_client('test') + source_directory = await share_client.create_directory("dir1") + dest_directory = await share_client.create_directory("dir2") + dest_file = dest_directory.get_file_client("test") file_attributes = NTFSAttributes(read_only=True) await dest_file.create_file(1024, file_attributes=file_attributes) # Act new_directory = await source_directory.rename_directory( - dest_directory.directory_path + '/' + dest_file.file_name, - overwrite=True, ignore_read_only=True) + dest_directory.directory_path + "/" + dest_file.file_name, overwrite=True, ignore_read_only=True + ) # Assert props = await new_directory.get_directory_properties() @@ -1322,10 +1350,10 @@ async def test_rename_directory_file_permission(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) file_permission_key = await share_client.create_permission_for_share(TEST_FILE_PERMISSIONS) - source_directory = await share_client.create_directory('dir1') + source_directory = await share_client.create_directory("dir1") # Act - new_directory = await source_directory.rename_directory('dir2', file_permission=TEST_FILE_PERMISSIONS) + new_directory = await source_directory.rename_directory("dir2", file_permission=TEST_FILE_PERMISSIONS) # Assert props = await new_directory.get_directory_properties() @@ -1342,12 +1370,12 @@ async def test_rename_directory_preserve_permission(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = await share_client.create_directory('dir1', file_permission=TEST_FILE_PERMISSIONS) + source_directory = await share_client.create_directory("dir1", file_permission=TEST_FILE_PERMISSIONS) source_props = await source_directory.get_directory_properties() source_permission_key = source_props.permission_key # Act - new_directory = await source_directory.rename_directory('dir2', file_permission='preserve') + new_directory = await source_directory.rename_directory("dir2", file_permission="preserve") # Assert props = await new_directory.get_directory_properties() @@ -1364,7 +1392,7 @@ async def test_rename_directory_smb_properties(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = await share_client.create_directory('dir1') + source_directory = await share_client.create_directory("dir1") file_attributes = NTFSAttributes(read_only=True, directory=True) file_creation_time = datetime(2022, 1, 26, 10, 9, 30, 500000, tzinfo=timezone.utc) @@ -1373,17 +1401,18 @@ async def test_rename_directory_smb_properties(self, **kwargs): # Act new_directory = await source_directory.rename_directory( - 'dir2', + "dir2", file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, - file_change_time=file_change_time) + file_change_time=file_change_time, + ) # Assert props = await new_directory.get_directory_properties() assert props is not None assert props.is_directory - assert str(file_attributes) == props.file_attributes.replace(' ', '') + assert str(file_attributes), props.file_attributes.replace(" " == "") assert file_creation_time == props.creation_time assert file_last_write_time == props.last_write_time assert file_change_time == props.change_time @@ -1398,15 +1427,15 @@ async def test_rename_directory_dest_lease(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = await share_client.create_directory('dir1') - dest_directory = await share_client.create_directory('dir2') - dest_file = await dest_directory.upload_file('test', b'Hello World') - lease = await dest_file.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + source_directory = await share_client.create_directory("dir1") + dest_directory = await share_client.create_directory("dir2") + dest_file = await dest_directory.upload_file("test", b"Hello World") + lease = await dest_file.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act new_directory = await source_directory.rename_directory( - dest_directory.directory_path + '/' + dest_file.file_name, - overwrite=True, destination_lease=lease) + dest_directory.directory_path + "/" + dest_file.file_name, overwrite=True, destination_lease=lease + ) # Assert props = await new_directory.get_directory_properties() @@ -1429,16 +1458,16 @@ async def test_rename_directory_share_sas(self, **kwargs): share_client.share_name, share_client.credential.account_key, expiry=datetime.utcnow() + timedelta(hours=1), - permission=ShareSasPermissions(read=True, write=True)) + permission=ShareSasPermissions(read=True, write=True), + ) source_directory = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1', - credential=token) + self.account_url(storage_account_name, "file"), share_client.share_name, "dir1", credential=token + ) await source_directory.create_directory() # Act - new_directory = await source_directory.rename_directory('dir2' + '?' + token) + new_directory = await source_directory.rename_directory("dir2" + "?" + token) # Assert props = await new_directory.get_directory_properties() @@ -1453,14 +1482,16 @@ async def test_rename_directory_trailing_dot(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - dest_dir_name = 'dir2' + '.' + dest_dir_name = "dir2" + "." directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=storage_account_key.secret, allow_trailing_dot=True, - allow_source_trailing_dot=True) + allow_source_trailing_dot=True, + ) # Act await directory_client.create_directory() @@ -1479,20 +1510,22 @@ async def test_storage_account_audience_directory_client(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', - credential=storage_account_key.secret + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", + credential=storage_account_key.secret, ) await directory_client.exists() # Act token_credential = self.get_credential(ShareServiceClient, is_async=True) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=token_credential, token_intent=TEST_INTENT, - audience=f'https://{storage_account_name}.file.core.windows.net' + audience=f"https://{storage_account_name}.file.core.windows.net", ) # Assert @@ -1509,20 +1542,22 @@ async def test_bad_audience_directory_client(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', - credential=storage_account_key.secret + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", + credential=storage_account_key.secret, ) await directory_client.exists() # Act token_credential = self.get_credential(ShareServiceClient, is_async=True) directory_client = ShareDirectoryClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'dir1.', + self.account_url(storage_account_name, "file"), + share_client.share_name, + "dir1.", credential=token_credential, token_intent=TEST_INTENT, - audience='https://badaudience.file.core.windows.net' + audience=f"https://badaudience.file.core.windows.net", ) # Assert @@ -1536,17 +1571,19 @@ async def test_file_permission_format_directory(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - user_given_permission_sddl = ("O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" - "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" - "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL") - user_given_permission_binary = ("AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" - "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" - "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=") + user_given_permission_sddl = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL" + ) + user_given_permission_binary = ( + "AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" + "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" + "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=" + ) directory_client = await share_client.create_directory( - 'dir1', - file_permission=user_given_permission_binary, - file_permission_format="binary" + "dir1", file_permission=user_given_permission_binary, file_permission_format="binary" ) props = await directory_client.get_directory_properties() @@ -1554,8 +1591,7 @@ async def test_file_permission_format_directory(self, **kwargs): assert props.permission_key is not None await directory_client.set_http_headers( - file_permission=user_given_permission_binary, - file_permission_format="binary" + file_permission=user_given_permission_binary, file_permission_format="binary" ) props = await directory_client.get_directory_properties() @@ -1563,23 +1599,19 @@ async def test_file_permission_format_directory(self, **kwargs): assert props.permission_key is not None server_returned_permission = await share_client.get_permission_for_share( - props.permission_key, - file_permission_format="sddl" + props.permission_key, file_permission_format="sddl" ) assert server_returned_permission == user_given_permission_sddl new_directory_client = await directory_client.rename_directory( - 'dir2', - file_permission=user_given_permission_binary, - file_permission_format="binary" + "dir2", file_permission=user_given_permission_binary, file_permission_format="binary" ) props = await new_directory_client.get_directory_properties() assert props is not None assert props.permission_key is not None server_returned_permission = await share_client.get_permission_for_share( - props.permission_key, - file_permission_format="binary" + props.permission_key, file_permission_format="binary" ) assert server_returned_permission == user_given_permission_binary @@ -1594,18 +1626,19 @@ async def test_create_directory_semantics(self, **kwargs): await self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - directory = await share_client.create_directory('dir1', file_property_semantics=None) + directory = await share_client.create_directory("dir1", file_property_semantics=None) props = await directory.get_directory_properties() assert props is not None - directory = await share_client.create_directory('dir2', file_property_semantics='New') + directory = await share_client.create_directory("dir2", file_property_semantics="New") props = await directory.get_directory_properties() assert props is not None directory = await share_client.create_directory( - 'dir3', file_property_semantics='Restore', file_permission=TEST_FILE_PERMISSIONS + "dir3", file_property_semantics="Restore", file_permission=TEST_FILE_PERMISSIONS ) props = await directory.get_directory_properties() assert props is not None + # ------------------------------------------------------------------------------ diff --git a/sdk/storage/azure-storage-file-share/tests/test_file.py b/sdk/storage/azure-storage-file-share/tests/test_file.py index 0ab9522021e2..a046a1d8f1f6 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -9,15 +10,14 @@ import pytest import requests - -from devtools_testutils import recorded_by_proxy -from devtools_testutils.storage import StorageRecordedTestCase -from settings.testcase import FileSharePreparer -from test_helpers import MockStorageTransport, ProgressTracker - from azure.core import MatchConditions from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential -from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, +) from azure.storage.blob import BlobServiceClient from azure.storage.fileshare import ( AccessPolicy, @@ -35,16 +35,22 @@ StorageErrorCode, ) +from devtools_testutils import recorded_by_proxy +from devtools_testutils.storage import StorageRecordedTestCase +from settings.testcase import FileSharePreparer +from test_helpers import MockStorageTransport, ProgressTracker # ------------------------------------------------------------------------------ -TEST_SHARE_PREFIX = 'share' -TEST_BLOB_PREFIX = 'blob' -TEST_DIRECTORY_PREFIX = 'dir' -TEST_FILE_PREFIX = 'file' +TEST_SHARE_PREFIX = "share" +TEST_BLOB_PREFIX = "blob" +TEST_DIRECTORY_PREFIX = "dir" +TEST_FILE_PREFIX = "file" LARGE_FILE_SIZE = 64 * 1024 + 5 -TEST_FILE_PERMISSIONS = 'O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-' \ - '1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;' \ - 'S-1-5-21-397955417-626881126-188441444-3053964)' +TEST_FILE_PERMISSIONS = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)" +) TEST_INTENT = "backup" # ------------------------------------------------------------------------------ @@ -61,8 +67,8 @@ def _setup(self, storage_account_name, storage_account_key, rmt_account=None, rm # the tests would take too long to execute self.fsc = ShareServiceClient(url, credential=credential.secret, max_range_size=4 * 1024) self.bsc = BlobServiceClient(blob_url, credential=credential.secret) - self.share_name = self.get_resource_name('utshare') - self.source_container_name = self.get_resource_name('sourceshare') + self.share_name = self.get_resource_name("utshare") + self.source_container_name = self.get_resource_name("sourceshare") if self.is_live: try: self.fsc.create_share(self.share_name) @@ -96,7 +102,7 @@ def _create_source_blob(self): except: pass blob_client = self.bsc.get_blob_client(self.source_container_name, self.get_resource_name(TEST_BLOB_PREFIX)) - blob_client.upload_blob(b'abcdefghijklmnop' * 32, overwrite=True) + blob_client.upload_blob(b"abcdefghijklmnop" * 32, overwrite=True) return blob_client def _create_empty_file(self, file_name=None, file_size=2048): @@ -113,7 +119,7 @@ def _get_file_client(self): return file_client def _create_remote_share(self): - self.remote_share_name = self.get_resource_name('remoteshare') + self.remote_share_name = self.get_resource_name("remoteshare") remote_share = self.fsc2.get_share_client(self.remote_share_name) try: remote_share.create_share() @@ -123,7 +129,7 @@ def _create_remote_share(self): def _create_remote_file(self, file_data=None): if not file_data: - file_data = b'12345678' * 1024 + file_data = b"12345678" * 1024 source_file_name = self._get_file_reference() remote_share = self.fsc2.get_share_client(self.remote_share_name) remote_file = remote_share.get_file_client(source_file_name) @@ -135,13 +141,13 @@ def _wait_for_async_copy(self, share_name, file_path): share_client = self.fsc.get_share_client(share_name) file_client = share_client.get_file_client(file_path) properties = file_client.get_file_properties() - while properties.copy.status != 'success': + while properties.copy.status != "success": count = count + 1 if count > 15: - pytest.fail('Timed out waiting for async copy to complete.') + pytest.fail("Timed out waiting for async copy to complete.") self.sleep(6) properties = file_client.get_file_properties() - assert properties.copy.status == 'success' + assert properties.copy.status == "success" def assertFileEqual(self, file_client, expected_data, **kwargs): actual_data = file_client.download_file(**kwargs).readall() @@ -173,7 +179,7 @@ def test_make_file_url(self, **kwargs): res = file_client.url # Assert - assert res == ('https://' + storage_account_name + '.file.core.windows.net/vhds/vhd_dir/my.vhd') + assert res == ("https://" + storage_account_name + ".file.core.windows.net/vhds/vhd_dir/my.vhd") @FileSharePreparer() @recorded_by_proxy @@ -189,7 +195,7 @@ def test_make_file_url_no_directory(self, **kwargs): res = file_client.url # Assert - assert res == ('https://' + storage_account_name + '.file.core.windows.net/vhds/my.vhd') + assert res == ("https://" + storage_account_name + ".file.core.windows.net/vhds/my.vhd") @FileSharePreparer() @recorded_by_proxy @@ -198,7 +204,7 @@ def test_make_file_url_with_protocol(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - url = self.account_url(storage_account_name, "file").replace('https', 'http') + url = self.account_url(storage_account_name, "file").replace("https", "http") fsc = ShareServiceClient(url, credential=storage_account_key.secret) share = fsc.get_share_client("vhds") file_client = share.get_file_client("vhd_dir/my.vhd") @@ -207,7 +213,7 @@ def test_make_file_url_with_protocol(self, **kwargs): res = file_client.url # Assert - assert res == ('http://' + storage_account_name + '.file.core.windows.net/vhds/vhd_dir/my.vhd') + assert res == ("http://" + storage_account_name + ".file.core.windows.net/vhds/vhd_dir/my.vhd") @FileSharePreparer() @recorded_by_proxy @@ -217,20 +223,19 @@ def test_make_file_url_with_sas(self, **kwargs): self._setup(storage_account_name, storage_account_key) # cspell:disable-next-line - sas = ('?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&' - 'sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D') + sas = "?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name="vhds", file_path="vhd_dir/my.vhd", - credential=sas + credential=sas, ) # Act res = file_client.url # Assert - assert res == ('https://' + storage_account_name + '.file.core.windows.net/vhds/vhd_dir/my.vhd{}'.format(sas)) + assert res == ("https://" + storage_account_name + ".file.core.windows.net/vhds/vhd_dir/my.vhd{}".format(sas)) @FileSharePreparer() @recorded_by_proxy @@ -244,7 +249,8 @@ def test_exists(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act / Assert assert not file_client.exists() @@ -264,7 +270,8 @@ def test_create_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act resp = file_client.create_file(1024, file_attributes="hidden") @@ -275,8 +282,8 @@ def test_create_file(self, **kwargs): assert props.lease is not None assert props.lease.state is not None assert props.lease.status is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] @FileSharePreparer() @recorded_by_proxy @@ -292,7 +299,8 @@ def test_create_file_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act resp = file_client.create_file(1024) @@ -303,8 +311,8 @@ def test_create_file_with_oauth(self, **kwargs): assert props.lease is not None assert props.lease.state is not None assert props.lease.status is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] @FileSharePreparer() @recorded_by_proxy @@ -336,9 +344,10 @@ def test_create_file_with_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) # Act resp = file_client.create_file(1024) @@ -349,9 +358,9 @@ def test_create_file_with_trailing_dot(self, **kwargs): assert props.lease is not None assert props.lease.state is not None assert props.lease.status is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] - assert props.name == file_name + '.' + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy @@ -364,9 +373,10 @@ def test_create_file_with_trailing_dot_false(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=False) + allow_trailing_dot=False, + ) # Act resp = file_client.create_file(1024) @@ -375,9 +385,10 @@ def test_create_file_with_trailing_dot_false(self, **kwargs): file_client_dotted = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=False) + allow_trailing_dot=False, + ) # create file client without dot file_client_no_dot = ShareFileClient( @@ -385,17 +396,18 @@ def test_create_file_with_trailing_dot_false(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - allow_trailing_dot=False) + allow_trailing_dot=False, + ) props = file_client.get_file_properties() props_dotted = file_client_dotted.get_file_properties() props_no_dot = file_client_no_dot.get_file_properties() # Assert - assert props.name == file_name + '.' - assert props.path == file_name + '.' - assert props_dotted.name == file_name + '.' - assert props_dotted.path == file_name + '.' + assert props.name == file_name + "." + assert props.path == file_name + "." + assert props_dotted.name == file_name + "." + assert props_dotted.path == file_name + "." assert props_no_dot.name == file_name assert props_no_dot.path == file_name @@ -406,13 +418,14 @@ def test_create_file_with_metadata(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} file_name = self._get_file_reference() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act resp = file_client.create_file(1024, metadata=metadata) @@ -420,8 +433,8 @@ def test_create_file_with_metadata(self, **kwargs): # Assert props = file_client.get_file_properties() assert props is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] assert props.metadata == metadata @FileSharePreparer() @@ -431,14 +444,15 @@ def test_create_file_with_metadata_with_trailing_dot(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} file_name = self._get_file_reference() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) # Act resp = file_client.create_file(1024, metadata=metadata) @@ -446,10 +460,10 @@ def test_create_file_with_metadata_with_trailing_dot(self, **kwargs): # Assert props = file_client.get_file_properties() assert props is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] assert props.metadata == metadata - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy @@ -475,6 +489,45 @@ def test_create_file_with_invalid_file_permission(self, **kwargs): with pytest.raises(HttpResponseError): file_name.create_file(1024, file_permission="abcde") + @FileSharePreparer() + @recorded_by_proxy + def test_create_file_semantics(self, **kwargs): + storage_account_name = kwargs.pop("storage_account_name") + storage_account_key = kwargs.pop("storage_account_key") + + self._setup(storage_account_name, storage_account_key) + file_name = self._get_file_reference() + + file1 = ShareFileClient( + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + "file1", + credential=storage_account_key.secret, + ) + file1.create_file(1024, file_property_semantics=None) + props = file1.get_file_properties() + assert props is not None + + file2 = ShareFileClient( + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + "file2", + credential=storage_account_key.secret, + ) + file2.create_file(1024, file_property_semantics="New") + props = file2.get_file_properties() + assert props is not None + + file3 = ShareFileClient( + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + "file2", + credential=storage_account_key.secret, + ) + file3.create_file(1024, file_property_semantics="Restore", file_permission=TEST_FILE_PERMISSIONS) + props = file3.get_file_properties() + assert props is not None + @FileSharePreparer() @recorded_by_proxy def test_create_file_with_lease(self, **kwargs): @@ -485,7 +538,7 @@ def test_create_file_with_lease(self, **kwargs): file_client = self._get_file_client() file_client.create_file(1024) - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") resp = file_client.create_file(1024, lease=lease) assert resp is not None @@ -510,10 +563,11 @@ def test_create_file_with_lease_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) file_client.create_file(1024) - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") resp = file_client.create_file(1024, lease=lease) assert resp is not None @@ -534,9 +588,9 @@ def test_create_file_with_changed_lease(self, **kwargs): file_client = self._get_file_client() file_client.create_file(1024) - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") old_lease_id = lease.id - lease.change('44444444-3333-2222-1111-000000000000') + lease.change("44444444-3333-2222-1111-000000000000") # use the old lease id to create file will throw exception. with pytest.raises(HttpResponseError): @@ -561,12 +615,13 @@ def test_create_file_with_changed_lease_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) file_client.create_file(1024) - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") old_lease_id = lease.id - lease.change('44444444-3333-2222-1111-000000000000') + lease.change("44444444-3333-2222-1111-000000000000") # use the old lease id to create file will throw exception. with pytest.raises(HttpResponseError): @@ -588,14 +643,15 @@ def test_lease_operations_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) file_client.create_file(1024) - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") old_lease_id = lease.id - lease.change('44444444-3333-2222-1111-000000000000') + lease.change("44444444-3333-2222-1111-000000000000") # use the old lease id to create file will throw exception. with pytest.raises(HttpResponseError): @@ -613,7 +669,7 @@ def test_lease_operations_trailing_dot(self, **kwargs): # Assert assert resp is not None - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy @@ -646,7 +702,8 @@ def test_create_file_set_smb_properties(self, **kwargs): file_attributes = NTFSAttributes(read_only=True, archive=True) file_creation_time = file_last_write_time = file_change_time = datetime( - 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc) + 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc + ) # Act file_client.create_file( @@ -654,7 +711,8 @@ def test_create_file_set_smb_properties(self, **kwargs): file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, - file_change_time=file_change_time) + file_change_time=file_change_time, + ) file_properties = file_client.get_file_properties() # Assert @@ -662,8 +720,8 @@ def test_create_file_set_smb_properties(self, **kwargs): assert file_creation_time == file_properties.creation_time assert file_last_write_time == file_properties.last_write_time assert file_change_time == file_properties.change_time - assert 'ReadOnly' in file_properties.file_attributes - assert 'Archive' in file_properties.file_attributes + assert "ReadOnly" in file_properties.file_attributes + assert "Archive" in file_properties.file_attributes @FileSharePreparer() @recorded_by_proxy @@ -692,7 +750,8 @@ def test_file_not_exists(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path="missingdir/" + file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act with pytest.raises(ResourceNotFoundError): @@ -718,7 +777,8 @@ def test_file_exists_with_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) props = snapshot_client.get_file_properties() # Assert @@ -769,7 +829,8 @@ def test_file_not_exists_with_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Assert with pytest.raises(ResourceNotFoundError): @@ -799,7 +860,7 @@ def test_resize_file_with_lease(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_client = self._create_file() - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act with pytest.raises(HttpResponseError): @@ -820,9 +881,7 @@ def test_set_file_properties(self, **kwargs): file_client = self._create_file() # Act - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") resp = file_client.set_http_headers(content_settings=content_settings) # Assert @@ -856,14 +915,10 @@ def test_set_datetime_all_ms_precision(self, **kwargs): ] # Act / Assert - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") for date1, date2 in zip(date_times[::2], date_times[1::2]): file_client.set_http_headers( - content_settings=content_settings, - file_creation_time=date1, - file_last_write_time=date2 + content_settings=content_settings, file_creation_time=date1, file_last_write_time=date2 ) @FileSharePreparer() @@ -877,15 +932,14 @@ def test_set_file_properties_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) file_client.create_file(1024) # Act - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") resp = file_client.set_http_headers(content_settings=content_settings) # Assert @@ -895,7 +949,7 @@ def test_set_file_properties_trailing_dot(self, **kwargs): assert properties.last_write_time is not None assert properties.creation_time is not None assert properties.permission_key is not None - assert properties.name == file_name + '.' + assert properties.name == file_name + "." @FileSharePreparer() @recorded_by_proxy @@ -907,9 +961,7 @@ def test_set_file_properties_with_file_permission(self, **kwargs): file_client = self._create_file() properties_on_creation = file_client.get_file_properties() - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") ntfs_attributes = NTFSAttributes(archive=True, temporary=True) last_write_time = properties_on_creation.last_write_time + timedelta(hours=3) @@ -922,7 +974,7 @@ def test_set_file_properties_with_file_permission(self, **kwargs): file_attributes=ntfs_attributes, file_last_write_time=last_write_time, file_creation_time=creation_time, - file_change_time=change_time + file_change_time=change_time, ) # Assert @@ -949,11 +1001,12 @@ def test_set_file_properties_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act file_client.create_file(1024) - content_settings = ContentSettings(content_language='spanish', content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") resp = file_client.set_http_headers(content_settings=content_settings) # Assert @@ -994,7 +1047,8 @@ def test_get_file_properties_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act resp = file_client.create_file(1024) @@ -1015,9 +1069,10 @@ def test_get_file_properties_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) resp = file_client.create_file(1024) # Ensure allow_trailing_dot=True is enforced properly by attempting to construct without trailing dot @@ -1025,7 +1080,8 @@ def test_get_file_properties_trailing_dot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) with pytest.raises(HttpResponseError): file_client_no_dot.get_file_properties() @@ -1043,11 +1099,11 @@ def test_get_file_properties_with_invalid_lease_fails(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_client = self._create_file() - file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act with pytest.raises(HttpResponseError): - file_client.get_file_properties(lease='44444444-3333-2222-1111-000000000000') + file_client.get_file_properties(lease="44444444-3333-2222-1111-000000000000") # get properties on a leased file will succeed properties = file_client.get_file_properties() @@ -1079,7 +1135,8 @@ def test_get_file_properties_with_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) snapshot_props = snapshot_client.get_file_properties() # Assert @@ -1106,7 +1163,8 @@ def test_get_file_metadata_with_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) metadata2 = {"test100": "foo100", "test200": "bar200"} file_client.set_file_metadata(metadata2) @@ -1131,7 +1189,8 @@ def test_get_file_properties_with_non_existing_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act with pytest.raises(ResourceNotFoundError): @@ -1162,7 +1221,7 @@ def test_set_file_metadata_with_upper_case(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42', 'UP': 'UPval'} + metadata = {"hello": "world", "number": "42", "UP": "UPval"} file_client = self._create_file() # Act @@ -1171,10 +1230,10 @@ def test_set_file_metadata_with_upper_case(self, **kwargs): # Assert md = file_client.get_file_properties().metadata assert 3 == len(md) - assert md['hello'] == 'world' - assert md['number'] == '42' - assert md['UP'] == 'UPval' - assert not 'up' in md + assert md["hello"] == "world" + assert md["number"] == "42" + assert md["UP"] == "UPval" + assert not "up" in md @FileSharePreparer() @recorded_by_proxy @@ -1190,8 +1249,9 @@ def test_set_file_metadata_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) - metadata = {'hello': 'world', 'number': '42', 'UP': 'UPval'} + token_intent=TEST_INTENT, + ) + metadata = {"hello": "world", "number": "42", "UP": "UPval"} # Act file_client.create_file(1024) @@ -1200,10 +1260,10 @@ def test_set_file_metadata_with_oauth(self, **kwargs): # Assert md = file_client.get_file_properties().metadata assert 3 == len(md) - assert md['hello'] == 'world' - assert md['number'] == '42' - assert md['UP'] == 'UPval' - assert not 'up' in md + assert md["hello"] == "world" + assert md["number"] == "42" + assert md["UP"] == "UPval" + assert not "up" in md @FileSharePreparer() @recorded_by_proxy @@ -1213,7 +1273,7 @@ def test_break_lease_with_broken_period_fails(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_client = self._create_file() - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Assert assert lease is not None @@ -1227,10 +1287,10 @@ def test_set_file_metadata_with_broken_lease(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42', 'UP': 'UPval'} + metadata = {"hello": "world", "number": "42", "UP": "UPval"} file_client = self._create_file() - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") with pytest.raises(HttpResponseError): file_client.set_file_metadata(metadata) @@ -1238,12 +1298,12 @@ def test_set_file_metadata_with_broken_lease(self, **kwargs): lease.break_lease() # lease is broken, set metadata doesn't require a lease - file_client.set_file_metadata({'hello': 'world'}) + file_client.set_file_metadata({"hello": "world"}) # Act md = file_client.get_file_properties().metadata # Assert assert 1 == len(md) - assert md['hello'] == 'world' + assert md["hello"] == "world" # Act file_client.acquire_lease(lease_id=lease_id_to_be_broken) @@ -1252,10 +1312,10 @@ def test_set_file_metadata_with_broken_lease(self, **kwargs): # Assert md = file_client.get_file_properties().metadata assert 3 == len(md) - assert md['hello'] == 'world' - assert md['number'] == '42' - assert md['UP'] == 'UPval' - assert not 'up' in md + assert md["hello"] == "world" + assert md["number"] == "42" + assert md["UP"] == "UPval" + assert not "up" in md @FileSharePreparer() @recorded_by_proxy @@ -1287,7 +1347,8 @@ def test_delete_file_with_existing_file_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act file_client.create_file(1024) @@ -1308,9 +1369,10 @@ def test_delete_file_with_existing_file_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) resp = file_client.create_file(1024) # Act @@ -1332,7 +1394,8 @@ def test_delete_file_with_non_existing_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act with pytest.raises(ResourceNotFoundError): @@ -1350,7 +1413,7 @@ def test_update_range(self, **kwargs): file_client = self._create_file() # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 file_client.upload_range(data, offset=0, length=512) # Assert @@ -1370,13 +1433,14 @@ def test_update_range_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) file_client.upload_file(self.short_byte_data) # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 file_client.upload_range(data, offset=0, length=512) props = file_client.get_file_properties() @@ -1385,7 +1449,7 @@ def test_update_range_trailing_dot(self, **kwargs): assert len(data) == 512 assert data == content[:512] assert self.short_byte_data[512:] == content[512:] - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy @@ -1395,10 +1459,10 @@ def test_update_range_with_lease(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_client = self._create_file() - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 with pytest.raises(HttpResponseError): file_client.upload_range(data, offset=0, length=512) @@ -1420,7 +1484,7 @@ def test_update_range_with_md5(self, **kwargs): file_client = self._create_file() # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 file_client.upload_range(data, offset=0, length=512, validate_content=True) # Assert @@ -1436,13 +1500,14 @@ def test_update_range_with_oauth(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1', + file_path="file1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act file_client.create_file(1024) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 file_client.upload_range(data, offset=0, length=512) @FileSharePreparer() @@ -1456,7 +1521,7 @@ def test_update_range_last_written_mode_now(self, **kwargs): current_last_write_time = file_client.get_file_properties().last_write_time # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 file_client.upload_range(data, offset=0, length=512, file_last_write_mode="Now") # Assert @@ -1474,7 +1539,7 @@ def test_update_range_last_written_mode_preserve(self, **kwargs): current_last_write_time = file_client.get_file_properties().last_write_time # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 file_client.upload_range(data, offset=0, length=512, file_last_write_mode="Preserve") # Assert @@ -1488,10 +1553,10 @@ def test_update_range_from_file_url_when_source_file_does_not_have_enough_bytes( storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_name = 'testfile1' + source_file_name = "testfile1" source_file_client = self._create_file(source_file_name) - destination_file_name = 'filetoupdate' + destination_file_name = "filetoupdate" destination_file_client = self._create_file(destination_file_name) # generate SAS for the source file @@ -1502,10 +1567,10 @@ def test_update_range_from_file_url_when_source_file_does_not_have_enough_bytes( source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1) + expiry=datetime.utcnow() + timedelta(hours=1), ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act with pytest.raises(HttpResponseError): @@ -1519,12 +1584,12 @@ def test_update_range_from_file_url(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_name = 'testfile' + source_file_name = "testfile" source_file_client = self._create_file(file_name=source_file_name) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 resp = source_file_client.upload_range(data, offset=0, length=512) - destination_file_name = 'filetoupdate' + destination_file_name = "filetoupdate" destination_file_client = self._create_empty_file(file_name=destination_file_name) # generate SAS for the source file @@ -1535,21 +1600,27 @@ def test_update_range_from_file_url(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act - destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0, - source_etag=resp['etag'], - source_match_condition=MatchConditions.IfNotModified) + destination_file_client.upload_range_from_url( + source_file_url, + offset=0, + length=512, + source_offset=0, + source_etag=resp["etag"], + source_match_condition=MatchConditions.IfNotModified, + ) # Assert # To make sure the range of the file is actually updated file_ranges = destination_file_client.get_ranges() file_content = destination_file_client.download_file(offset=0, length=512).readall() assert 1 == len(file_ranges) - assert 0 == file_ranges[0].get('start') - assert 511 == file_ranges[0].get('end') + assert 0 == file_ranges[0].get("start") + assert 511 == file_ranges[0].get("end") assert data == file_content @FileSharePreparer() @@ -1560,16 +1631,18 @@ def test_update_range_from_file_url_with_oauth(self, **kwargs): self._setup(storage_account_name, storage_account_key) source_blob_client = self._create_source_blob() - token = "Bearer {}".format(self.get_credential(ShareServiceClient).get_token( - "https://storage.azure.com/.default").token) + token = "Bearer {}".format( + self.get_credential(ShareServiceClient).get_token("https://storage.azure.com/.default").token + ) - destination_file_name = 'filetoupdate' + destination_file_name = "filetoupdate" destination_file_client = self._create_empty_file(file_name=destination_file_name) with pytest.raises(HttpResponseError): destination_file_client.upload_range_from_url(source_blob_client.url, offset=0, length=512, source_offset=0) - destination_file_client.upload_range_from_url(source_blob_client.url, offset=0, length=512, source_offset=0, - source_authorization=token) + destination_file_client.upload_range_from_url( + source_blob_client.url, offset=0, length=512, source_offset=0, source_authorization=token + ) @FileSharePreparer() @recorded_by_proxy @@ -1578,14 +1651,14 @@ def test_update_range_from_file_url_with_lease(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_name = 'testfile' + source_file_name = "testfile" source_file_client = self._create_file(file_name=source_file_name) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 resp = source_file_client.upload_range(data, offset=0, length=512) - destination_file_name = 'filetoupdate' + destination_file_name = "filetoupdate" destination_file_client = self._create_empty_file(file_name=destination_file_name) - lease = destination_file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = destination_file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # generate SAS for the source file sas_token_for_source_file = self.generate_sas( @@ -1595,27 +1668,38 @@ def test_update_range_from_file_url_with_lease(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act with pytest.raises(HttpResponseError): - destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0, - source_etag=resp['etag'], - source_match_condition=MatchConditions.IfNotModified) + destination_file_client.upload_range_from_url( + source_file_url, + offset=0, + length=512, + source_offset=0, + source_etag=resp["etag"], + source_match_condition=MatchConditions.IfNotModified, + ) - destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0, - source_etag=resp['etag'], - source_match_condition=MatchConditions.IfNotModified, - lease=lease) + destination_file_client.upload_range_from_url( + source_file_url, + offset=0, + length=512, + source_offset=0, + source_etag=resp["etag"], + source_match_condition=MatchConditions.IfNotModified, + lease=lease, + ) # Assert # To make sure the range of the file is actually updated file_ranges = destination_file_client.get_ranges() file_content = destination_file_client.download_file(offset=0, length=512).readall() assert 1 == len(file_ranges) - assert 0 == file_ranges[0].get('start') - assert 511 == file_ranges[0].get('end') + assert 0 == file_ranges[0].get("start") + assert 511 == file_ranges[0].get("end") assert data == file_content @FileSharePreparer() @@ -1625,14 +1709,14 @@ def test_update_big_range_from_file_url(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_name = 'testfile1' + source_file_name = "testfile1" end = 1048575 source_file_client = self._create_empty_file(file_name=source_file_name, file_size=1024 * 1024) - data = b'abcdefghijklmnop' * 65536 - source_file_client.upload_range(data, offset=0, length=end+1) + data = b"abcdefghijklmnop" * 65536 + source_file_client.upload_range(data, offset=0, length=end + 1) - destination_file_name = 'filetoupdate1' + destination_file_name = "filetoupdate1" destination_file_client = self._create_empty_file(file_name=destination_file_name, file_size=1024 * 1024) # generate SAS for the source file @@ -1643,20 +1727,21 @@ def test_update_big_range_from_file_url(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act - destination_file_client.upload_range_from_url(source_file_url, offset=0, length=end+1, source_offset=0) + destination_file_client.upload_range_from_url(source_file_url, offset=0, length=end + 1, source_offset=0) # Assert # To make sure the range of the file is actually updated file_ranges = destination_file_client.get_ranges() file_content = destination_file_client.download_file(offset=0, length=end + 1).readall() assert 1 == len(file_ranges) - assert 0 == file_ranges[0].get('start') - assert end == file_ranges[0].get('end') + assert 0 == file_ranges[0].get("start") + assert end == file_ranges[0].get("end") assert data == file_content @FileSharePreparer() @@ -1666,11 +1751,11 @@ def test_update_range_from_file_url_last_written_mode_now(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_client = self._create_file(file_name='testfile') - data = b'abcdefghijklmnop' * 32 + source_file_client = self._create_file(file_name="testfile") + data = b"abcdefghijklmnop" * 32 source_file_client.upload_range(data, offset=0, length=512) - destination_file_client = self._create_empty_file(file_name='filetoupdate') + destination_file_client = self._create_empty_file(file_name="filetoupdate") current_last_write_time = destination_file_client.get_file_properties().last_write_time # generate SAS for the source file @@ -1681,13 +1766,15 @@ def test_update_range_from_file_url_last_written_mode_now(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act - destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0, - file_last_write_mode="Now") + destination_file_client.upload_range_from_url( + source_file_url, offset=0, length=512, source_offset=0, file_last_write_mode="Now" + ) # Assert new_last_write_time = destination_file_client.get_file_properties().last_write_time @@ -1700,11 +1787,11 @@ def test_update_range_from_file_url_last_written_mode_preserve(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_client = self._create_file(file_name='testfile') - data = b'abcdefghijklmnop' * 32 + source_file_client = self._create_file(file_name="testfile") + data = b"abcdefghijklmnop" * 32 source_file_client.upload_range(data, offset=0, length=512) - destination_file_client = self._create_empty_file(file_name='filetoupdate') + destination_file_client = self._create_empty_file(file_name="filetoupdate") current_last_write_time = destination_file_client.get_file_properties().last_write_time # generate SAS for the source file @@ -1715,13 +1802,15 @@ def test_update_range_from_file_url_last_written_mode_preserve(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act - destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0, - file_last_write_mode="Preserve") + destination_file_client.upload_range_from_url( + source_file_url, offset=0, length=512, source_offset=0, file_last_write_mode="Preserve" + ) # Assert new_last_write_time = destination_file_client.get_file_properties().last_write_time @@ -1741,7 +1830,7 @@ def test_clear_range(self, **kwargs): # Assert content = file_client.download_file().readall() - assert b'\x00' * 512 == content[:512] + assert b"\x00" * 512 == content[:512] assert self.short_byte_data[512:] == content[512:] @FileSharePreparer() @@ -1755,9 +1844,10 @@ def test_clear_range_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) file_client.upload_file(self.short_byte_data) # Act @@ -1766,9 +1856,9 @@ def test_clear_range_trailing_dot(self, **kwargs): # Assert content = file_client.download_file().readall() - assert b'\x00' * 512 == content[:512] + assert b"\x00" * 512 == content[:512] assert self.short_byte_data[512:] == content[512:] - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy @@ -1780,10 +1870,10 @@ def test_update_file_unicode(self, **kwargs): file_client = self._create_file() # Act - data = 'abcdefghijklmnop' * 32 + data = "abcdefghijklmnop" * 32 file_client.upload_range(data, offset=0, length=512) - encoded = data.encode('utf-8') + encoded = data.encode("utf-8") # Assert content = file_client.download_file().readall() @@ -1804,7 +1894,8 @@ def test_list_ranges_none(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.create_file(1024) # Act @@ -1825,9 +1916,10 @@ def test_list_ranges_none_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) file_client.create_file(1024) # Act @@ -1837,7 +1929,7 @@ def test_list_ranges_none_trailing_dot(self, **kwargs): # Assert assert ranges is not None assert len(ranges) == 0 - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy @@ -1851,14 +1943,15 @@ def test_list_ranges_none_with_invalid_lease_fails(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.create_file(1024) - file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act with pytest.raises(HttpResponseError): - file_client.get_ranges(lease='44444444-3333-2222-1111-000000000000') + file_client.get_ranges(lease="44444444-3333-2222-1111-000000000000") # Get ranges on a leased file will succeed without provide the lease ranges = file_client.get_ranges() @@ -1879,7 +1972,8 @@ def test_list_ranges_diff(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.create_file(2048) share_client = self.fsc.get_share_client(self.share_name) @@ -1891,7 +1985,7 @@ def test_list_ranges_diff(self, **kwargs): file_client.clear_range(offset=512, length=512) ranges1, cleared1 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot1) - ranges2, cleared2 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot2['snapshot']) + ranges2, cleared2 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot2["snapshot"]) # Assert assert ranges1 is not None @@ -1899,20 +1993,20 @@ def test_list_ranges_diff(self, **kwargs): assert len(ranges1) == 2 assert isinstance(cleared1, list) assert len(cleared1) == 1 - assert ranges1[0]['start'] == 0 - assert ranges1[0]['end'] == 511 - assert cleared1[0]['start'] == 512 - assert cleared1[0]['end'] == 1023 - assert ranges1[1]['start'] == 1024 - assert ranges1[1]['end'] == 1535 + assert ranges1[0]["start"] == 0 + assert ranges1[0]["end"] == 511 + assert cleared1[0]["start"] == 512 + assert cleared1[0]["end"] == 1023 + assert ranges1[1]["start"] == 1024 + assert ranges1[1]["end"] == 1535 assert ranges2 is not None assert isinstance(ranges2, list) assert len(ranges2) == 0 assert isinstance(cleared2, list) assert len(cleared2) == 1 - assert cleared2[0]['start'] == 512 - assert cleared2[0]['end'] == 1023 + assert cleared2[0]["start"] == 512 + assert cleared2[0]["end"] == 1023 @FileSharePreparer() @recorded_by_proxy @@ -1928,7 +2022,8 @@ def test_list_ranges_diff_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) file_client.create_file(2048) share_client = self.fsc.get_share_client(self.share_name) @@ -1940,7 +2035,7 @@ def test_list_ranges_diff_with_oauth(self, **kwargs): file_client.clear_range(offset=512, length=512) ranges1, cleared1 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot1) - ranges2, cleared2 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot2['snapshot']) + ranges2, cleared2 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot2["snapshot"]) # Assert assert ranges1 is not None @@ -1948,20 +2043,20 @@ def test_list_ranges_diff_with_oauth(self, **kwargs): assert len(ranges1) == 2 assert isinstance(cleared1, list) assert len(cleared1) == 1 - assert ranges1[0]['start'] == 0 - assert ranges1[0]['end'] == 511 - assert cleared1[0]['start'] == 512 - assert cleared1[0]['end'] == 1023 - assert ranges1[1]['start'] == 1024 - assert ranges1[1]['end'] == 1535 + assert ranges1[0]["start"] == 0 + assert ranges1[0]["end"] == 511 + assert cleared1[0]["start"] == 512 + assert cleared1[0]["end"] == 1023 + assert ranges1[1]["start"] == 1024 + assert ranges1[1]["end"] == 1535 assert ranges2 is not None assert isinstance(ranges2, list) assert len(ranges2) == 0 assert isinstance(cleared2, list) assert len(cleared2) == 1 - assert cleared2[0]['start'] == 512 - assert cleared2[0]['end'] == 1023 + assert cleared2[0]["start"] == 512 + assert cleared2[0]["end"] == 1023 @FileSharePreparer() @recorded_by_proxy @@ -1974,9 +2069,10 @@ def test_list_ranges_diff_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) file_client.create_file(2048) share_client = self.fsc.get_share_client(self.share_name) @@ -1988,7 +2084,7 @@ def test_list_ranges_diff_trailing_dot(self, **kwargs): file_client.clear_range(offset=512, length=512) ranges1, cleared1 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot1) - ranges2, cleared2 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot2['snapshot']) + ranges2, cleared2 = file_client.get_ranges_diff(previous_sharesnapshot=snapshot2["snapshot"]) props = file_client.get_file_properties() # Assert @@ -1997,22 +2093,22 @@ def test_list_ranges_diff_trailing_dot(self, **kwargs): assert len(ranges1) == 2 assert isinstance(cleared1, list) assert len(cleared1) == 1 - assert ranges1[0]['start'] == 0 - assert ranges1[0]['end'] == 511 - assert cleared1[0]['start'] == 512 - assert cleared1[0]['end'] == 1023 - assert ranges1[1]['start'] == 1024 - assert ranges1[1]['end'] == 1535 + assert ranges1[0]["start"] == 0 + assert ranges1[0]["end"] == 511 + assert cleared1[0]["start"] == 512 + assert cleared1[0]["end"] == 1023 + assert ranges1[1]["start"] == 1024 + assert ranges1[1]["end"] == 1535 assert ranges2 is not None assert isinstance(ranges2, list) assert len(ranges2) == 0 assert isinstance(cleared2, list) assert len(cleared2) == 1 - assert cleared2[0]['start'] == 512 - assert cleared2[0]['end'] == 1023 + assert cleared2[0]["start"] == 512 + assert cleared2[0]["end"] == 1023 - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy @@ -2026,7 +2122,8 @@ def test_list_ranges_diff_support_rename(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.create_file(2048) share_client = self.fsc.get_share_client(self.share_name) @@ -2037,7 +2134,7 @@ def test_list_ranges_diff_support_rename(self, **kwargs): previous_snapshot = share_client.create_snapshot() file_client.clear_range(offset=512, length=512) file_client.upload_range(data2, offset=512, length=512) - file_client = file_client.rename_file(file_name + 'renamed') + file_client = file_client.rename_file(file_name + "renamed") # Assert with pytest.raises(ResourceExistsError): @@ -2050,8 +2147,8 @@ def test_list_ranges_diff_support_rename(self, **kwargs): assert len(ranges) == 1 assert isinstance(cleared, list) assert len(cleared) == 0 - assert ranges[0]['start'] == 512 - assert ranges[0]['end'] == 1023 + assert ranges[0]["start"] == 512 + assert ranges[0]["end"] == 1023 @FileSharePreparer() @recorded_by_proxy @@ -2065,10 +2162,11 @@ def test_list_ranges_2(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.create_file(2048) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 resp1 = file_client.upload_range(data, offset=0, length=512) resp2 = file_client.upload_range(data, offset=1024, length=512) @@ -2078,10 +2176,10 @@ def test_list_ranges_2(self, **kwargs): # Assert assert ranges is not None assert len(ranges) == 2 - assert ranges[0]['start'] == 0 - assert ranges[0]['end'] == 511 - assert ranges[1]['start'] == 1024 - assert ranges[1]['end'] == 1535 + assert ranges[0]["start"] == 0 + assert ranges[0]["end"] == 511 + assert ranges[1]["start"] == 1024 + assert ranges[1]["end"] == 1535 @FileSharePreparer() @recorded_by_proxy @@ -2095,7 +2193,8 @@ def test_list_ranges_none_from_snapshot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.create_file(1024) share_client = self.fsc.get_share_client(self.share_name) @@ -2105,7 +2204,8 @@ def test_list_ranges_none_from_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.delete_file() @@ -2130,7 +2230,8 @@ def test_list_ranges_none_from_snapshot_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) file_client.create_file(1024) share_client = self.fsc.get_share_client(self.share_name) @@ -2141,7 +2242,8 @@ def test_list_ranges_none_from_snapshot_with_oauth(self, **kwargs): file_path=file_client.file_name, snapshot=snapshot, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) file_client.delete_file() @@ -2164,9 +2266,10 @@ def test_list_ranges_2_from_snapshot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.create_file(2048) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 resp1 = file_client.upload_range(data, offset=0, length=512) resp2 = file_client.upload_range(data, offset=1024, length=512) @@ -2177,7 +2280,8 @@ def test_list_ranges_2_from_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.delete_file() @@ -2187,10 +2291,10 @@ def test_list_ranges_2_from_snapshot(self, **kwargs): # Assert assert ranges is not None assert len(ranges) == 2 - assert ranges[0]['start'] == 0 - assert ranges[0]['end'] == 511 - assert ranges[1]['start'] == 1024 - assert ranges[1]['end'] == 1535 + assert ranges[0]["start"] == 0 + assert ranges[0]["end"] == 511 + assert ranges[1]["start"] == 1024 + assert ranges[1]["end"] == 1535 @FileSharePreparer() @recorded_by_proxy @@ -2203,16 +2307,17 @@ def test_copy_file_with_existing_file(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) # Act copy = file_client.start_copy_from_url(source_client.url) # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = file_client.download_file().readall() assert copy_file == self.short_byte_data @@ -2229,17 +2334,18 @@ def test_copy_file_with_existing_file_oauth(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', + file_path="file1copy", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act copy = file_client.start_copy_from_url(source_client.url) # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = file_client.download_file().readall() assert copy_file == self.short_byte_data @@ -2255,26 +2361,28 @@ def test_copy_file_with_existing_file_trailing_dot(self, **kwargs): source_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) source_client.upload_file(self.short_byte_data) dest_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy.', + file_path="file1copy.", credential=storage_account_key.secret, allow_trailing_dot=True, - allow_source_trailing_dot=True) + allow_source_trailing_dot=True, + ) # Act copy = dest_client.start_copy_from_url(source_client.url) # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = dest_client.download_file().readall() assert copy_file == self.short_byte_data @@ -2290,10 +2398,11 @@ def test_copy_existing_file_with_lease(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) file_client.create_file(1024) - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act with pytest.raises(HttpResponseError): @@ -2303,8 +2412,8 @@ def test_copy_existing_file_with_lease(self, **kwargs): # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = file_client.download_file().readall() assert copy_file == self.short_byte_data @@ -2320,8 +2429,9 @@ def test_copy_file_ignore_readonly(self, **kwargs): dest_file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) file_attributes = NTFSAttributes(read_only=True) dest_file.create_file(1024, file_attributes=file_attributes) @@ -2334,8 +2444,8 @@ def test_copy_file_ignore_readonly(self, **kwargs): # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = dest_file.download_file().readall() assert copy_file == self.short_byte_data @@ -2351,8 +2461,9 @@ def test_copy_file_with_specifying_acl_copy_behavior_attributes(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) source_props = source_client.get_file_properties() file_creation_time = source_props.creation_time - timedelta(hours=1) @@ -2374,15 +2485,15 @@ def test_copy_file_with_specifying_acl_copy_behavior_attributes(self, **kwargs): # Assert dest_prop = file_client.get_file_properties() # to make sure the attributes are the same as the set ones - assert file_creation_time == dest_prop['creation_time'] - assert file_last_write_time == dest_prop['last_write_time'] - assert file_change_time == dest_prop['change_time'] - assert 'Temporary' in dest_prop['file_attributes'] - assert 'NoScrubData' in dest_prop['file_attributes'] + assert file_creation_time == dest_prop["creation_time"] + assert file_last_write_time == dest_prop["last_write_time"] + assert file_change_time == dest_prop["change_time"] + assert "Temporary" in dest_prop["file_attributes"] + assert "NoScrubData" in dest_prop["file_attributes"] assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = file_client.download_file().readall() assert copy_file == self.short_byte_data @@ -2400,23 +2511,21 @@ def test_copy_file_with_specifying_acl_and_attributes_from_source(self, **kwargs file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) # Act - copy = file_client.start_copy_from_url( - source_client.url, - permission_key='source' - ) + copy = file_client.start_copy_from_url(source_client.url, permission_key="source") # Assert dest_prop = file_client.get_file_properties() # to make sure the acl is copied from source - assert source_prop['permission_key'] == dest_prop['permission_key'] + assert source_prop["permission_key"] == dest_prop["permission_key"] assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = file_client.download_file().readall() assert copy_file == self.short_byte_data @@ -2433,18 +2542,19 @@ def test_copy_file_async_private_file(self, **kwargs): storage_account_name, storage_account_key, secondary_storage_account_name, - secondary_storage_account_key.secret + secondary_storage_account_key.secret, ) self._create_remote_share() source_file = self._create_remote_file() # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) with pytest.raises(HttpResponseError) as e: file_client.start_copy_from_url(source_file.url) @@ -2462,9 +2572,9 @@ def test_copy_file_async_private_file_with_sas(self, **kwargs): storage_account_name, storage_account_key, secondary_storage_account_name, - secondary_storage_account_key.secret + secondary_storage_account_key.secret, ) - data = b'12345678' * 1024 + data = b"12345678" * 1024 self._create_remote_share() source_file = self._create_remote_file(file_data=data) sas_token = self.generate_sas( @@ -2476,19 +2586,20 @@ def test_copy_file_async_private_file_with_sas(self, **kwargs): permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), ) - source_url = source_file.url + '?' + sas_token + source_url = source_file.url + "?" + sas_token # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) copy_resp = file_client.start_copy_from_url(source_url) # Assert - assert copy_resp['copy_status'] in ['success', 'pending'] + assert copy_resp["copy_status"] in ["success", "pending"] self._wait_for_async_copy(self.share_name, target_file_name) actual_data = file_client.download_file().readall() @@ -2506,9 +2617,9 @@ def test_abort_copy_file(self, **kwargs): storage_account_name, storage_account_key, secondary_storage_account_name, - secondary_storage_account_key.secret + secondary_storage_account_key.secret, ) - data = b'12345678' * 1024 * 1024 + data = b"12345678" * 1024 * 1024 self._create_remote_share() source_file = self._create_remote_file(file_data=data) sas_token = self.generate_sas( @@ -2520,23 +2631,24 @@ def test_abort_copy_file(self, **kwargs): permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), ) - source_url = source_file.url + '?' + sas_token + source_url = source_file.url + "?" + sas_token # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) copy_resp = file_client.start_copy_from_url(source_url) - assert copy_resp['copy_status'] == 'pending' + assert copy_resp["copy_status"] == "pending" file_client.abort_copy(copy_resp) # Assert target_file = file_client.download_file() - assert target_file.readall() == b'' - assert target_file.properties.copy.status == 'aborted' + assert target_file.readall() == b"" + assert target_file.properties.copy.status == "aborted" @pytest.mark.live_test_only @FileSharePreparer() @@ -2547,9 +2659,13 @@ def test_abort_copy_file_with_oauth(self, **kwargs): secondary_storage_account_key = kwargs.pop("secondary_storage_account_key") token_credential = self.get_credential(ShareServiceClient) - self._setup(storage_account_name, storage_account_key, secondary_storage_account_name, - secondary_storage_account_key.secret) - data = b'12345678' * 1024 * 1024 + self._setup( + storage_account_name, + storage_account_key, + secondary_storage_account_name, + secondary_storage_account_key.secret, + ) + data = b"12345678" * 1024 * 1024 self._create_remote_share() source_file = self._create_remote_file(file_data=data) sas_token = self.generate_sas( @@ -2561,24 +2677,25 @@ def test_abort_copy_file_with_oauth(self, **kwargs): permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), ) - source_url = source_file.url + '?' + sas_token + source_url = source_file.url + "?" + sas_token # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) copy_resp = file_client.start_copy_from_url(source_url) - assert copy_resp['copy_status'] == 'pending' + assert copy_resp["copy_status"] == "pending" file_client.abort_copy(copy_resp) # Assert target_file = file_client.download_file() - assert target_file.readall() == b'' - assert target_file.properties.copy.status == 'aborted' + assert target_file.readall() == b"" + assert target_file.properties.copy.status == "aborted" @FileSharePreparer() @recorded_by_proxy @@ -2590,19 +2707,20 @@ def test_abort_copy_file_with_synchronous_copy_fails(self, **kwargs): source_file = self._create_file() # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) copy_resp = file_client.start_copy_from_url(source_file.url) with pytest.raises(HttpResponseError): file_client.abort_copy(copy_resp) # Assert - assert copy_resp['copy_status'] == 'success' + assert copy_resp["copy_status"] == "success" @FileSharePreparer() @recorded_by_proxy @@ -2611,19 +2729,20 @@ def test_unicode_get_file_unicode_name(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_name = '啊齄丂狛狜' + file_name = "啊齄丂狛狜" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) - file_client.upload_file(b'hello world') + credential=storage_account_key.secret, + ) + file_client.upload_file(b"hello world") # Act content = file_client.download_file().readall() # Assert - assert content == b'hello world' + assert content == b"hello world" @FileSharePreparer() @recorded_by_proxy @@ -2632,28 +2751,29 @@ def test_unicode_get_file_unicode_name_with_lease(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_name = '啊齄丂狛狜' + file_name = "啊齄丂狛狜" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.create_file(1024) - lease = file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") with pytest.raises(HttpResponseError): - file_client.upload_file(b'hello world') + file_client.upload_file(b"hello world") - file_client.upload_file(b'hello world', lease=lease) + file_client.upload_file(b"hello world", lease=lease) # Act # download the file with a wrong lease id will fail with pytest.raises(HttpResponseError): - file_client.upload_file(b'hello world', lease='44444444-3333-2222-1111-000000000000') + file_client.upload_file(b"hello world", lease="44444444-3333-2222-1111-000000000000") content = file_client.download_file(lease=lease).readall() # Assert - assert content == b'hello world' + assert content == b"hello world" @FileSharePreparer() @recorded_by_proxy @@ -2667,10 +2787,11 @@ def test_file_unicode_data(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act - data = 'hello world啊齄丂狛狜'.encode('utf-8') + data = "hello world啊齄丂狛狜".encode("utf-8") file_client.upload_file(data) # Assert @@ -2687,14 +2808,14 @@ def test_file_unicode_data_and_file_attributes(self, **kwargs): file_client = self._get_file_client() # Act - data = 'hello world啊齄丂狛狜'.encode('utf-8') + data = "hello world啊齄丂狛狜".encode("utf-8") file_client.upload_file(data, file_attributes=NTFSAttributes(temporary=True)) # Assert content = file_client.download_file().readall() properties = file_client.get_file_properties() assert content == data - assert 'Temporary' in properties.file_attributes + assert "Temporary" in properties.file_attributes @FileSharePreparer() @recorded_by_proxy @@ -2703,22 +2824,7 @@ def test_unicode_get_file_binary_data(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - base64_data = ( - 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0' - 'xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYm' - 'ZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm' - '5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM' - '0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gI' - 'GCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNz' - 's/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRob' - 'HB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2h' - 'pamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tb' - 'a3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECA' - 'wQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9Q' - 'UVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2' - 'en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6' - 'uvs7e7v8PHy8/T19vf4+fr7/P3+/w==' - ) + base64_data = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==" binary_data = base64.b64decode(base64_data) file_name = self._get_file_reference() @@ -2726,7 +2832,8 @@ def test_unicode_get_file_binary_data(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) file_client.upload_file(binary_data) # Act @@ -2749,20 +2856,22 @@ def test_create_file_from_bytes_with_progress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act progress = [] + def callback(response): - current = response.context['upload_stream_current'] - total = response.context['data_stream_total'] + current = response.context["upload_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) response = file_client.upload_file(data, max_concurrency=2, raw_response_hook=callback) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert self.assertFileEqual(file_client, data) @@ -2782,13 +2891,14 @@ def test_create_file_from_bytes_with_index(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act response = file_client.upload_file(data[index:], max_concurrency=2) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert self.assertFileEqual(file_client, data[1024:]) @@ -2809,16 +2919,17 @@ def test_create_file_from_bytes_with_index_and_count(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act response = file_client.upload_file(data[index:], length=count, max_concurrency=2) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert - self.assertFileEqual(file_client, data[index:index + count]) + self.assertFileEqual(file_client, data[index : index + count]) @pytest.mark.live_test_only @FileSharePreparer() @@ -2834,7 +2945,8 @@ def test_create_file_from_path(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -2842,8 +2954,8 @@ def test_create_file_from_path(self, **kwargs): temp_file.seek(0) response = file_client.upload_file(temp_file, max_concurrency=2) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert self.assertFileEqual(file_client, data) @@ -2862,13 +2974,15 @@ def test_create_file_from_path_with_progress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act progress = [] + def callback(response): - current = response.context['upload_stream_current'] - total = response.context['data_stream_total'] + current = response.context["upload_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -2877,8 +2991,8 @@ def callback(response): temp_file.seek(0) response = file_client.upload_file(temp_file, max_concurrency=2, raw_response_hook=callback) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert self.assertFileEqual(file_client, data) @@ -2898,7 +3012,8 @@ def test_create_file_from_stream(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_size = len(data) @@ -2907,8 +3022,8 @@ def test_create_file_from_stream(self, **kwargs): temp_file.seek(0) response = file_client.upload_file(temp_file, max_concurrency=2) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert self.assertFileEqual(file_client, data[:file_size]) @@ -2927,7 +3042,8 @@ def test_create_file_from_stream_non_seekable(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_size = len(data) @@ -2954,13 +3070,15 @@ def test_create_file_from_stream_with_progress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act progress = [] + def callback(response): - current = response.context['upload_stream_current'] - total = response.context['data_stream_total'] + current = response.context["upload_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -2988,7 +3106,8 @@ def test_create_file_from_stream_truncated(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_size = len(data) - 512 @@ -3014,13 +3133,15 @@ def test_create_file_from_stream_with_progress_truncated(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act progress = [] + def callback(response): - current = response.context['upload_stream_current'] - total = response.context['data_stream_total'] + current = response.context["upload_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -3042,14 +3163,15 @@ def test_create_file_from_text(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_name = self._get_file_reference() - text = 'hello 啊齄丂狛狜 world' - data = text.encode('utf-8') + text = "hello 啊齄丂狛狜 world" + data = text.encode("utf-8") file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_client.upload_file(text) @@ -3065,17 +3187,18 @@ def test_create_file_from_text_with_encoding(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_name = self._get_file_reference() - text = 'hello 啊齄丂狛狜 world' - data = text.encode('utf-16') + text = "hello 啊齄丂狛狜 world" + data = text.encode("utf-16") file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act - file_client.upload_file(text, encoding='UTF-16') + file_client.upload_file(text, encoding="UTF-16") # Assert self.assertFileEqual(file_client, data) @@ -3089,13 +3212,14 @@ def test_create_file_from_text_chunked_upload(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_name = self._get_file_reference() data = self.get_random_text_data(LARGE_FILE_SIZE) - encoded_data = data.encode('utf-8') + encoded_data = data.encode("utf-8") file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_client.upload_file(data) @@ -3117,7 +3241,8 @@ def test_create_file_with_md5_small(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_client.upload_file(data, validate_content=True) @@ -3138,7 +3263,8 @@ def test_create_file_with_md5_large(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_client.upload_file(data, validate_content=True, max_concurrency=2) @@ -3159,9 +3285,10 @@ def test_create_file_progress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=1024) + max_range_size=1024, + ) - data = b'a' * 5 * 1024 + data = b"a" * 5 * 1024 progress = ProgressTracker(len(data), 1024) # Act @@ -3185,9 +3312,10 @@ def test_create_file_progress_parallel(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=1024) + max_range_size=1024, + ) - data = b'a' * 5 * 1024 + data = b"a" * 5 * 1024 progress = ProgressTracker(len(data), 1024) # Act @@ -3220,7 +3348,8 @@ def test_sas_access_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=token) + credential=token, + ) content = file_client.download_file().readall() # Assert @@ -3231,19 +3360,19 @@ def test_sas_access_file(self, **kwargs): def test_sas_signed_identifier(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - variables = kwargs.pop('variables', {}) + variables = kwargs.pop("variables", {}) self._setup(storage_account_name, storage_account_key) file_client = self._create_file() share_client = self.fsc.get_share_client(self.share_name) access_policy = AccessPolicy() - start_time = self.get_datetime_variable(variables, 'start_time', datetime.utcnow() - timedelta(hours=1)) - expiry_time = self.get_datetime_variable(variables, 'expiry_time', datetime.utcnow() + timedelta(hours=1)) + start_time = self.get_datetime_variable(variables, "start_time", datetime.utcnow() - timedelta(hours=1)) + expiry_time = self.get_datetime_variable(variables, "expiry_time", datetime.utcnow() + timedelta(hours=1)) access_policy.start = start_time access_policy.expiry = expiry_time access_policy.permission = FileSasPermissions(read=True) - identifiers = {'testid': access_policy} + identifiers = {"testid": access_policy} share_client.set_share_access_policy(identifiers) token = self.generate_sas( @@ -3252,12 +3381,11 @@ def test_sas_signed_identifier(self, **kwargs): file_client.share_name, file_client.file_path, file_client.credential.account_key, - policy_id='testid') + policy_id="testid", + ) # Act - sas_file = ShareFileClient.from_file_url( - file_client.url, - credential=token) + sas_file = ShareFileClient.from_file_url(file_client.url, credential=token) content = file_client.download_file().readall() @@ -3288,9 +3416,10 @@ def test_account_sas(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=token) + credential=token, + ) - response = requests.get(file_client.url, timeout=15) + response = requests.get(file_client.url) # Assert assert response.ok @@ -3318,7 +3447,8 @@ def test_account_sas_credential(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=AzureSasCredential(token)) + credential=AzureSasCredential(token), + ) properties = file_client.get_file_properties() @@ -3331,7 +3461,6 @@ def test_azure_named_key_credential_access(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - self._setup(storage_account_name, storage_account_key) file_client = self._create_file() named_key = AzureNamedKeyCredential(storage_account_name, storage_account_key.secret) @@ -3341,7 +3470,8 @@ def test_azure_named_key_credential_access(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=named_key) + credential=named_key, + ) properties = file_client.get_file_properties() @@ -3357,7 +3487,8 @@ def test_account_sas_raises_if_sas_already_in_uri(self, **kwargs): self.account_url(storage_account_name, "file") + "?sig=foo", share_name="foo", file_path="foo", - credential=AzureSasCredential("?foo=bar")) + credential=AzureSasCredential("?foo=bar"), + ) @pytest.mark.live_test_only @FileSharePreparer() @@ -3382,8 +3513,9 @@ def test_shared_read_access_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=token) - response = requests.get(file_client.url, timeout=15) + credential=token, + ) + response = requests.get(file_client.url) # Assert assert response.ok @@ -3405,11 +3537,11 @@ def test_shared_read_access_file_with_content_query_params(self, **kwargs): file_client.credential.account_key, permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), - cache_control='no-cache', - content_disposition='inline', - content_encoding='utf-8', - content_language='fr', - content_type='text', + cache_control="no-cache", + content_disposition="inline", + content_encoding="utf-8", + content_language="fr", + content_type="text", ) # Act @@ -3417,16 +3549,17 @@ def test_shared_read_access_file_with_content_query_params(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=token) - response = requests.get(file_client.url, timeout=15) + credential=token, + ) + response = requests.get(file_client.url) # Assert assert self.short_byte_data == response.content - assert response.headers['cache-control'] == 'no-cache' - assert response.headers['content-disposition'] == 'inline' - assert response.headers['content-encoding'] == 'utf-8' - assert response.headers['content-language'] == 'fr' - assert response.headers['content-type'] == 'text' + assert response.headers["cache-control"] == "no-cache" + assert response.headers["content-disposition"] == "inline" + assert response.headers["content-encoding"] == "utf-8" + assert response.headers["content-language"] == "fr" + assert response.headers["content-type"] == "text" @pytest.mark.live_test_only @FileSharePreparer() @@ -3435,7 +3568,7 @@ def test_shared_write_access_file(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - updated_data = b'updated file data' + updated_data = b"updated file data" file_client_admin = self._create_file() token = self.generate_sas( generate_file_sas, @@ -3450,16 +3583,17 @@ def test_shared_write_access_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client_admin.file_name, - credential=token) + credential=token, + ) # Act - headers = {'x-ms-range': 'bytes=0-16', 'x-ms-write': 'update'} - response = requests.put(file_client.url + '&comp=range', headers=headers, data=updated_data, timeout=15) + headers = {"x-ms-range": "bytes=0-16", "x-ms-write": "update"} + response = requests.put(file_client.url + "&comp=range", headers=headers, data=updated_data) # Assert assert response.ok file_content = file_client_admin.download_file().readall() - assert updated_data == file_content[:len(updated_data)] + assert updated_data == file_content[: len(updated_data)] @pytest.mark.live_test_only @FileSharePreparer() @@ -3482,10 +3616,11 @@ def test_shared_delete_access_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client_admin.file_name, - credential=token) + credential=token, + ) # Act - response = requests.delete(file_client.url, timeout=15) + response = requests.delete(file_client.url) # Assert assert response.ok @@ -3499,13 +3634,13 @@ def test_rename_file(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file = self._create_file('file1') + source_file = self._create_file("file1") # Act - new_file = source_file.rename_file('file2') + new_file = source_file.rename_file("file2") # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = new_file.get_file_properties() assert props is not None @@ -3523,14 +3658,15 @@ def test_rename_file_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act file_client.create_file(1024) - new_file = file_client.rename_file('file2') + new_file = file_client.rename_file("file2") # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = new_file.get_file_properties() assert props is not None @@ -3543,15 +3679,15 @@ def test_rename_file_different_directory(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = share_client.create_directory('dir1') - dest_directory = share_client.create_directory('dir2') - source_file = source_directory.upload_file('file1', self.short_byte_data) + source_directory = share_client.create_directory("dir1") + dest_directory = share_client.create_directory("dir2") + source_file = source_directory.upload_file("file1", self.short_byte_data) # Act - new_file = source_file.rename_file(dest_directory.directory_path + '/' + source_file.file_name) + new_file = source_file.rename_file(dest_directory.directory_path + "/" + source_file.file_name) # Assert - assert 'dir2' in new_file.file_path + assert "dir2" in new_file.file_path props = new_file.get_file_properties() assert props is not None @@ -3564,9 +3700,9 @@ def test_rename_file_ignore_readonly(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_file = share_client.get_file_client('file1') + source_file = share_client.get_file_client("file1") source_file.create_file(1024) - dest_file = share_client.get_file_client('file2') + dest_file = share_client.get_file_client("file2") file_attributes = NTFSAttributes(read_only=True) dest_file.create_file(1024, file_attributes=file_attributes) @@ -3575,7 +3711,7 @@ def test_rename_file_ignore_readonly(self, **kwargs): new_file = source_file.rename_file(dest_file.file_name, overwrite=True, ignore_read_only=True) # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = new_file.get_file_properties() assert props is not None @@ -3589,11 +3725,11 @@ def test_rename_file_file_permission(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) file_permission_key = share_client.create_permission_for_share(TEST_FILE_PERMISSIONS) - source_file = share_client.get_file_client('file1') + source_file = share_client.get_file_client("file1") source_file.create_file(1024) # Act - new_file = source_file.rename_file('file2', file_permission=TEST_FILE_PERMISSIONS) + new_file = source_file.rename_file("file2", file_permission=TEST_FILE_PERMISSIONS) # Assert props = new_file.get_file_properties() @@ -3609,14 +3745,14 @@ def test_rename_file_preserve_permission(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_file = share_client.get_file_client('file1') + source_file = share_client.get_file_client("file1") source_file.create_file(1024, file_permission=TEST_FILE_PERMISSIONS) source_props = source_file.get_file_properties() source_permission_key = source_props.permission_key # Act - new_file = source_file.rename_file('file2', file_permission='preserve') + new_file = source_file.rename_file("file2", file_permission="preserve") # Assert props = new_file.get_file_properties() @@ -3630,7 +3766,7 @@ def test_rename_file_smb_properties(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file = self._create_file('file1') + source_file = self._create_file("file1") file_attributes = NTFSAttributes(read_only=True, archive=True) file_creation_time = datetime(2022, 1, 26, 10, 9, 30, 500000, tzinfo=timezone.utc) @@ -3639,17 +3775,17 @@ def test_rename_file_smb_properties(self, **kwargs): # Act new_file = source_file.rename_file( - 'file2', + "file2", file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, - file_change_time=file_change_time + file_change_time=file_change_time, ) # Assert props = new_file.get_file_properties() assert props is not None - assert str(file_attributes).replace(' ', '') == props.file_attributes.replace(' ', '') + assert str(file_attributes), props.file_attributes.replace(" " == "") assert file_creation_time == props.creation_time assert file_last_write_time == props.last_write_time assert file_change_time == props.change_time @@ -3661,13 +3797,11 @@ def test_rename_file_content_type(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file = self._create_file('file1') - content_type = 'text/plain' + source_file = self._create_file("file1") + content_type = "text/plain" # Act - new_file = source_file.rename_file( - 'file2', - content_type=content_type) + new_file = source_file.rename_file("file2", content_type=content_type) # Assert props = new_file.get_file_properties() @@ -3682,20 +3816,18 @@ def test_rename_file_with_lease(self, **kwargs): self._setup(storage_account_name, storage_account_key) - source_file = self._create_file('file1') - dest_file = self._create_file('file2') - source_lease = source_file.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') - dest_lease = dest_file.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + source_file = self._create_file("file1") + dest_file = self._create_file("file2") + source_lease = source_file.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") + dest_lease = dest_file.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act new_file = source_file.rename_file( - dest_file.file_name, - overwrite=True, - source_lease=source_lease, - destination_lease=dest_lease) + dest_file.file_name, overwrite=True, source_lease=source_lease, destination_lease=dest_lease + ) # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = new_file.get_file_properties() assert props is not None @@ -3714,19 +3846,19 @@ def test_rename_file_share_sas(self, **kwargs): share_client.share_name, share_client.credential.account_key, expiry=datetime.utcnow() + timedelta(hours=1), - permission=ShareSasPermissions(read=True, write=True)) + permission=ShareSasPermissions(read=True, write=True), + ) source_file = ShareFileClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'file1', - credential=token) + self.account_url(storage_account_name, "file"), share_client.share_name, "file1", credential=token + ) source_file.create_file(1024) # Act - new_file = source_file.rename_file('file2' + '?' + token) + new_file = source_file.rename_file("file2" + "?" + token) # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = new_file.get_file_properties() assert props is not None @@ -3743,7 +3875,7 @@ def test_storage_account_audience_file_client(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) file_client.create_file(1024) @@ -3758,7 +3890,7 @@ def test_storage_account_audience_file_client(self, **kwargs): file_path=file_name, credential=token_credential, token_intent=TEST_INTENT, - audience=f'https://{storage_account_name}.file.core.windows.net' + audience=f"https://{storage_account_name}.file.core.windows.net", ) # Assert @@ -3778,7 +3910,7 @@ def test_bad_audience_file_client(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) file_client.create_file(1024) @@ -3793,7 +3925,7 @@ def test_bad_audience_file_client(self, **kwargs): file_path=file_name, credential=token_credential, token_intent=TEST_INTENT, - audience='https://badaudience.file.core.windows.net' + audience=f"https://badaudience.file.core.windows.net", ) # Assert @@ -3807,20 +3939,20 @@ def test_file_permission_format(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_file = share_client.get_file_client('file1') - user_given_permission_sddl = ("O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" - "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" - "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL") - user_given_permission_binary = ("AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" - "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" - "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=") + source_file = share_client.get_file_client("file1") + user_given_permission_sddl = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL" + ) + user_given_permission_binary = ( + "AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" + "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" + "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=" + ) # Create file - source_file.create_file( - 1024, - file_permission=user_given_permission_binary, - file_permission_format="binary" - ) + source_file.create_file(1024, file_permission=user_given_permission_binary, file_permission_format="binary") props = source_file.get_file_properties() assert props is not None @@ -3828,29 +3960,23 @@ def test_file_permission_format(self, **kwargs): # Rename file new_file = source_file.rename_file( - 'file2', - file_permission=user_given_permission_binary, - file_permission_format="binary" + "file2", file_permission=user_given_permission_binary, file_permission_format="binary" ) props = new_file.get_file_properties() assert props is not None assert props.permission_key is not None server_returned_permission = share_client.get_permission_for_share( - props.permission_key, - file_permission_format="binary" + props.permission_key, file_permission_format="binary" ) assert server_returned_permission == user_given_permission_binary # Set HTTP headers - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline' - ) + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") new_file.set_http_headers( content_settings=content_settings, file_permission=user_given_permission_binary, - file_permission_format="binary" + file_permission_format="binary", ) props = new_file.get_file_properties() assert props is not None @@ -3859,8 +3985,7 @@ def test_file_permission_format(self, **kwargs): assert props.content_settings.content_disposition == content_settings.content_disposition server_returned_permission = share_client.get_permission_for_share( - props.permission_key, - file_permission_format="sddl" + props.permission_key, file_permission_format="sddl" ) assert server_returned_permission == user_given_permission_sddl @@ -3868,17 +3993,15 @@ def test_file_permission_format(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='filecopy', - credential=storage_account_key.secret + file_path="filecopy", + credential=storage_account_key.secret, ) copy = file_client.start_copy_from_url( - new_file.url, - file_permission=user_given_permission_binary, - file_permission_format="binary" + new_file.url, file_permission=user_given_permission_binary, file_permission_format="binary" ) assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None new_file.delete_file() file_client.delete_file() @@ -3897,7 +4020,7 @@ def test_legacy_transport(self, **kwargs): file_path="filemocktransport", credential=storage_account_key.secret, transport=transport, - retry_total=0 + retry_total=0, ) data = file_client.download_file() @@ -3927,7 +4050,7 @@ def test_legacy_transport_with_content_validation(self, **kwargs): file_path="filemocktransport", credential=storage_account_key.secret, transport=transport, - retry_total=0 + retry_total=0, ) data = b"Hello World!" @@ -3946,17 +4069,12 @@ def test_upload_range_copy_source_error_and_status_code(self, **kwargs): self._setup(storage_account_name, storage_account_key) try: - source_file_client = self._create_file(file_name='sourcefile') - source_file_client.upload_range(b'abcdefghijklmnop' * 32, offset=0, length=512) - target_file_client = self._create_empty_file(file_name='targetfile') + source_file_client = self._create_file(file_name="sourcefile") + source_file_client.upload_range(b"abcdefghijklmnop" * 32, offset=0, length=512) + target_file_client = self._create_empty_file(file_name="targetfile") with pytest.raises(HttpResponseError) as e: - target_file_client.upload_range_from_url( - source_file_client.url, - offset=0, - length=512, - source_offset=0 - ) + target_file_client.upload_range_from_url(source_file_client.url, offset=0, length=512, source_offset=0) assert e.value.response.headers["x-ms-copy-source-status-code"] == "401" assert e.value.response.headers["x-ms-copy-source-error-code"] == "NoAuthenticationInformation" @@ -3976,12 +4094,11 @@ def test_download_file_decompress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024 + max_range_size=4 * 1024, ) - compressed_data = (b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xcaH\xcd\xc9\xc9WH+\xca\xcfUH' - b'\xaf\xca,\x00\x00\x00\x00\xff\xff\x03\x00d\xaa\x8e\xb5\x0f\x00\x00\x00') + compressed_data = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xcaH\xcd\xc9\xc9WH+\xca\xcfUH\xaf\xca,\x00\x00\x00\x00\xff\xff\x03\x00d\xaa\x8e\xb5\x0f\x00\x00\x00" decompressed_data = b"hello from gzip" - content_settings = ContentSettings(content_encoding='gzip') + content_settings = ContentSettings(content_encoding="gzip") # Act / Assert file_client.upload_file(data=compressed_data, content_settings=content_settings) @@ -4004,9 +4121,8 @@ def test_download_file_no_decompress_chunks(self, **kwargs): max_chunk_get_size=4, max_single_get_size=4, ) - compressed_data = (b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xcaH\xcd\xc9\xc9WH+\xca\xcfUH' - b'\xaf\xca,\x00\x00\x00\x00\xff\xff\x03\x00d\xaa\x8e\xb5\x0f\x00\x00\x00') - content_settings = ContentSettings(content_encoding='gzip') + compressed_data = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xcaH\xcd\xc9\xc9WH+\xca\xcfUH\xaf\xca,\x00\x00\x00\x00\xff\xff\x03\x00d\xaa\x8e\xb5\x0f\x00\x00\x00" + content_settings = ContentSettings(content_encoding="gzip") # Act / Assert file_client.upload_file(data=compressed_data, content_settings=content_settings) @@ -4027,7 +4143,8 @@ def test_upload_file_with_none_max_concurrency(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) data = b"hello world" @@ -4049,7 +4166,8 @@ def test_download_file_with_none_max_concurrency(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) data = b"hello world" file_client.upload_file(data) @@ -4073,7 +4191,7 @@ def test_create_file_semantics(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name + "file1", - credential=storage_account_key + credential=storage_account_key, ) file1.create_file(1024, file_property_semantics=None) props = file1.get_file_properties() @@ -4083,7 +4201,7 @@ def test_create_file_semantics(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name + "file2", - credential=storage_account_key + credential=storage_account_key, ) file2.create_file(1024, file_property_semantics="New") props = file2.get_file_properties() @@ -4093,7 +4211,7 @@ def test_create_file_semantics(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name + "file2", - credential=storage_account_key + credential=storage_account_key, ) file3.create_file(1024, file_property_semantics="Restore", file_permission=TEST_FILE_PERMISSIONS) props = file3.get_file_properties() @@ -4111,7 +4229,7 @@ def test_create_file_with_data(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name + "file", - credential=storage_account_key.secret + credential=storage_account_key.secret, ) size = 1024 data = b"abc" * size @@ -4119,4 +4237,5 @@ def test_create_file_with_data(self, **kwargs): downloaded_data = file_client.download_file().readall() assert downloaded_data == data + # ------------------------------------------------------------------------------ diff --git a/sdk/storage/azure-storage-file-share/tests/test_file_api_version.py b/sdk/storage/azure-storage-file-share/tests/test_file_api_version.py index 6d450be22723..e85c148fae68 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file_api_version.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file_api_version.py @@ -16,7 +16,7 @@ # ------------------------------------------------------------------------------ -TEST_FILE_PREFIX = 'file' +TEST_FILE_PREFIX = "file" class TestStorageClient(StorageRecordedTestCase): @@ -31,7 +31,7 @@ def _get_file_reference(self, prefix=TEST_FILE_PREFIX): return self.get_resource_name(prefix) def _create_share(self, fsc): - share_name = self.get_resource_name('utshare') + share_name = self.get_resource_name("utshare") share = fsc.get_share_client(share_name) try: share.create_share() @@ -46,14 +46,11 @@ def _delete_share(self, share): pass return share - # --Test Cases-------------------------------------------------------------- def test_service_client_api_version_property(self): self.setUp() - service_client = ShareServiceClient( - "https://foo.file.core.windows.net/account", - credential="fake_key") + service_client = ShareServiceClient("https://foo.file.core.windows.net/account", credential="fake_key") assert service_client.api_version == self.api_version_2 assert service_client._client._config.version == self.api_version_2 @@ -61,9 +58,8 @@ def test_service_client_api_version_property(self): service_client.api_version = self.api_version_1 service_client = ShareServiceClient( - "https://foo.file.core.windows.net/account", - credential="fake_key", - api_version=self.api_version_1) + "https://foo.file.core.windows.net/account", credential="fake_key", api_version=self.api_version_1 + ) assert service_client.api_version == self.api_version_1 assert service_client._client._config.version == self.api_version_1 @@ -73,10 +69,7 @@ def test_service_client_api_version_property(self): def test_share_client_api_version_property(self): self.setUp() - share_client = ShareClient( - "https://foo.file.core.windows.net/account", - "share_name", - credential="fake_key") + share_client = ShareClient("https://foo.file.core.windows.net/account", "share_name", credential="fake_key") assert share_client.api_version == self.api_version_2 assert share_client._client._config.version == self.api_version_2 @@ -84,7 +77,8 @@ def test_share_client_api_version_property(self): "https://foo.file.core.windows.net/account", "share_name", credential="fake_key", - api_version=self.api_version_1) + api_version=self.api_version_1, + ) assert share_client.api_version == self.api_version_1 assert share_client._client._config.version == self.api_version_1 @@ -99,10 +93,8 @@ def test_share_client_api_version_property(self): def test_directory_client_api_version_property(self): self.setUp() dir_client = ShareDirectoryClient( - "https://foo.file.core.windows.net/account", - "share_name", - "dir_path", - credential="fake_key") + "https://foo.file.core.windows.net/account", "share_name", "dir_path", credential="fake_key" + ) assert dir_client.api_version == self.api_version_2 assert dir_client._client._config.version == self.api_version_2 @@ -111,7 +103,8 @@ def test_directory_client_api_version_property(self): "share_name", "dir_path", credential="fake_key", - api_version=self.api_version_1) + api_version=self.api_version_1, + ) assert dir_client.api_version == self.api_version_1 assert dir_client._client._config.version == self.api_version_1 @@ -126,10 +119,8 @@ def test_directory_client_api_version_property(self): def test_file_client_api_version_property(self): self.setUp() file_client = ShareFileClient( - "https://foo.file.core.windows.net/account", - "share", - self._get_file_reference(), - credential="fake_key") + "https://foo.file.core.windows.net/account", "share", self._get_file_reference(), credential="fake_key" + ) assert file_client.api_version == self.api_version_2 assert file_client._client._config.version == self.api_version_2 @@ -138,25 +129,21 @@ def test_file_client_api_version_property(self): "share", self._get_file_reference(), credential="fake_key", - api_version=self.api_version_1) + api_version=self.api_version_1, + ) assert file_client.api_version == self.api_version_1 assert file_client._client._config.version == self.api_version_1 def test_invalid_api_version(self): self.setUp() with pytest.raises(ValueError) as error: - ShareServiceClient( - "https://foo.file.core.windows.net/account", - credential="fake_key", - api_version="foo") + ShareServiceClient("https://foo.file.core.windows.net/account", credential="fake_key", api_version="foo") assert str(error.value).startswith("Unsupported API version 'foo'.") with pytest.raises(ValueError) as error: ShareClient( - "https://foo.file.core.windows.net/account", - "share_name", - credential="fake_key", - api_version="foo") + "https://foo.file.core.windows.net/account", "share_name", credential="fake_key", api_version="foo" + ) assert str(error.value).startswith("Unsupported API version 'foo'.") with pytest.raises(ValueError) as error: @@ -165,7 +152,8 @@ def test_invalid_api_version(self): "share_name", "dir_path", credential="fake_key", - api_version="foo") + api_version="foo", + ) assert str(error.value).startswith("Unsupported API version 'foo'.") with pytest.raises(ValueError) as error: @@ -174,7 +162,8 @@ def test_invalid_api_version(self): "share", self._get_file_reference(), credential="fake_key", - api_version="foo") + api_version="foo", + ) assert str(error.value).startswith("Unsupported API version 'foo'.") @FileSharePreparer() @@ -188,7 +177,7 @@ def test_old_api_copy_file_succeeds(self, **kwargs): self.account_url(storage_account_name, "file"), credential=storage_account_key.secret, max_range_size=4 * 1024, - api_version=self.api_version_1 + api_version=self.api_version_1, ) share = self._create_share(fsc) file_name = self._get_file_reference() @@ -196,19 +185,20 @@ def test_old_api_copy_file_succeeds(self, **kwargs): source_client = share.get_file_client(file_name) source_client.upload_file( self.short_byte_data, - file_attributes='none', - file_creation_time='now', - file_last_write_time='now', - file_permission='inherit' + file_attributes="none", + file_creation_time="now", + file_last_write_time="now", + file_permission="inherit", ) source_prop = source_client.get_file_properties() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=share.share_name, - file_path='file1copy', + file_path="file1copy", credential=storage_account_key.secret, - api_version=self.api_version_1) + api_version=self.api_version_1, + ) # Act copy = file_client.start_copy_from_url(source_client.url) @@ -216,13 +206,14 @@ def test_old_api_copy_file_succeeds(self, **kwargs): # Assert dest_prop = file_client.get_file_properties() # to make sure the acl is copied from source - assert source_prop['permission_key'] == dest_prop['permission_key'] + assert source_prop["permission_key"] == dest_prop["permission_key"] assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = file_client.download_file().readall() assert copy_file == self.short_byte_data + # ------------------------------------------------------------------------------ diff --git a/sdk/storage/azure-storage-file-share/tests/test_file_api_version_async.py b/sdk/storage/azure-storage-file-share/tests/test_file_api_version_async.py index 064591eb7e05..b305398d93ab 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file_api_version_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file_api_version_async.py @@ -16,7 +16,7 @@ # ------------------------------------------------------------------------------ -TEST_FILE_PREFIX = 'file' +TEST_FILE_PREFIX = "file" class TestAsyncStorageClient(AsyncStorageRecordedTestCase): @@ -31,7 +31,7 @@ def _get_file_reference(self, prefix=TEST_FILE_PREFIX): return self.get_resource_name(prefix) async def _create_share(self, fsc): - share_name = self.get_resource_name('utshare') + share_name = self.get_resource_name("utshare") share = fsc.get_share_client(share_name) try: await share.create_share() @@ -46,14 +46,11 @@ async def _delete_share(self, share): pass return share - # --Test Cases-------------------------------------------------------------- def test_service_client_api_version_property(self): self.setUp() - service_client = ShareServiceClient( - "https://foo.file.core.windows.net/account", - credential="fake_key") + service_client = ShareServiceClient("https://foo.file.core.windows.net/account", credential="fake_key") assert service_client.api_version == self.api_version_2 assert service_client._client._config.version == self.api_version_2 @@ -61,9 +58,8 @@ def test_service_client_api_version_property(self): service_client.api_version = self.api_version_1 service_client = ShareServiceClient( - "https://foo.file.core.windows.net/account", - credential="fake_key", - api_version=self.api_version_1) + "https://foo.file.core.windows.net/account", credential="fake_key", api_version=self.api_version_1 + ) assert service_client.api_version == self.api_version_1 assert service_client._client._config.version == self.api_version_1 @@ -73,10 +69,7 @@ def test_service_client_api_version_property(self): def test_share_client_api_version_property(self): self.setUp() - share_client = ShareClient( - "https://foo.file.core.windows.net/account", - "share_name", - credential="fake_key") + share_client = ShareClient("https://foo.file.core.windows.net/account", "share_name", credential="fake_key") assert share_client.api_version == self.api_version_2 assert share_client._client._config.version == self.api_version_2 @@ -84,7 +77,8 @@ def test_share_client_api_version_property(self): "https://foo.file.core.windows.net/account", "share_name", credential="fake_key", - api_version=self.api_version_1) + api_version=self.api_version_1, + ) assert share_client.api_version == self.api_version_1 assert share_client._client._config.version == self.api_version_1 @@ -99,10 +93,8 @@ def test_share_client_api_version_property(self): def test_directory_client_api_version_property(self): self.setUp() dir_client = ShareDirectoryClient( - "https://foo.file.core.windows.net/account", - "share_name", - "dir_path", - credential="fake_key") + "https://foo.file.core.windows.net/account", "share_name", "dir_path", credential="fake_key" + ) assert dir_client.api_version == self.api_version_2 assert dir_client._client._config.version == self.api_version_2 @@ -111,7 +103,8 @@ def test_directory_client_api_version_property(self): "share_name", "dir_path", credential="fake_key", - api_version=self.api_version_1) + api_version=self.api_version_1, + ) assert dir_client.api_version == self.api_version_1 assert dir_client._client._config.version == self.api_version_1 @@ -126,10 +119,8 @@ def test_directory_client_api_version_property(self): def test_file_client_api_version_property(self): self.setUp() file_client = ShareFileClient( - "https://foo.file.core.windows.net/account", - "share", - self._get_file_reference(), - credential="fake_key") + "https://foo.file.core.windows.net/account", "share", self._get_file_reference(), credential="fake_key" + ) assert file_client.api_version == self.api_version_2 assert file_client._client._config.version == self.api_version_2 @@ -138,25 +129,21 @@ def test_file_client_api_version_property(self): "share", self._get_file_reference(), credential="fake_key", - api_version=self.api_version_1) + api_version=self.api_version_1, + ) assert file_client.api_version == self.api_version_1 assert file_client._client._config.version == self.api_version_1 def test_invalid_api_version(self): self.setUp() with pytest.raises(ValueError) as error: - ShareServiceClient( - "https://foo.file.core.windows.net/account", - credential="fake_key", - api_version="foo") + ShareServiceClient("https://foo.file.core.windows.net/account", credential="fake_key", api_version="foo") assert str(error.value).startswith("Unsupported API version 'foo'.") with pytest.raises(ValueError) as error: ShareClient( - "https://foo.file.core.windows.net/account", - "share_name", - credential="fake_key", - api_version="foo") + "https://foo.file.core.windows.net/account", "share_name", credential="fake_key", api_version="foo" + ) assert str(error.value).startswith("Unsupported API version 'foo'.") with pytest.raises(ValueError) as error: @@ -165,7 +152,8 @@ def test_invalid_api_version(self): "share_name", "dir_path", credential="fake_key", - api_version="foo") + api_version="foo", + ) assert str(error.value).startswith("Unsupported API version 'foo'.") with pytest.raises(ValueError) as error: @@ -174,7 +162,8 @@ def test_invalid_api_version(self): "share", self._get_file_reference(), credential="fake_key", - api_version="foo") + api_version="foo", + ) assert str(error.value).startswith("Unsupported API version 'foo'.") @FileSharePreparer() @@ -189,7 +178,7 @@ async def test_old_api_copy_file_succeeds(self, **kwargs): self.account_url(storage_account_name, "file"), credential=storage_account_key.secret, max_range_size=4 * 1024, - api_version=self.api_version_1 + api_version=self.api_version_1, ) share = await self._create_share(fsc) file_name = self._get_file_reference() @@ -197,19 +186,20 @@ async def test_old_api_copy_file_succeeds(self, **kwargs): source_client = share.get_file_client(file_name) await source_client.upload_file( self.short_byte_data, - file_attributes='none', - file_creation_time='now', - file_last_write_time='now', - file_permission='inherit' + file_attributes="none", + file_creation_time="now", + file_last_write_time="now", + file_permission="inherit", ) source_prop = await source_client.get_file_properties() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=share.share_name, - file_path='file1copy', + file_path="file1copy", credential=storage_account_key.secret, - api_version=self.api_version_1) + api_version=self.api_version_1, + ) # Act copy = await file_client.start_copy_from_url(source_client.url) @@ -217,13 +207,14 @@ async def test_old_api_copy_file_succeeds(self, **kwargs): # Assert dest_prop = await file_client.get_file_properties() # to make sure the acl is copied from source - assert source_prop['permission_key'] == dest_prop['permission_key'] + assert source_prop["permission_key"] == dest_prop["permission_key"] assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = await (await file_client.download_file()).readall() assert copy_file == self.short_byte_data + # ------------------------------------------------------------------------------ diff --git a/sdk/storage/azure-storage-file-share/tests/test_file_async.py b/sdk/storage/azure-storage-file-share/tests/test_file_async.py index 1d776aa8306c..b30bca211c6d 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -11,14 +12,13 @@ import pytest import requests - -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase -from settings.testcase import FileSharePreparer -from test_helpers_async import AsyncStream, MockStorageTransport, ProgressTracker - from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential -from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, +) from azure.storage.blob.aio import BlobServiceClient from azure.storage.fileshare import ( AccessPolicy, @@ -35,16 +35,22 @@ ) from azure.storage.fileshare.aio import ShareFileClient, ShareServiceClient +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase +from settings.testcase import FileSharePreparer +from test_helpers_async import AsyncStream, MockStorageTransport, ProgressTracker # ------------------------------------------------------------------------------ -TEST_SHARE_PREFIX = 'share' -TEST_DIRECTORY_PREFIX = 'dir' -TEST_FILE_PREFIX = 'file' -TEST_BLOB_PREFIX = 'blob' +TEST_SHARE_PREFIX = "share" +TEST_DIRECTORY_PREFIX = "dir" +TEST_FILE_PREFIX = "file" +TEST_BLOB_PREFIX = "blob" LARGE_FILE_SIZE = 64 * 1024 + 5 -TEST_FILE_PERMISSIONS = 'O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-' \ - '1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;' \ - 'S-1-5-21-397955417-626881126-188441444-3053964)' +TEST_FILE_PERMISSIONS = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)" +) TEST_INTENT = "backup" # ------------------------------------------------------------------------------ @@ -58,11 +64,10 @@ def _setup(self, storage_account_name, storage_account_key, rmt_account=None, rm # test chunking functionality by reducing the threshold # for chunking and the size of each chunk, otherwise # the tests would take too long to execute - self.fsc = ShareServiceClient( - url, credential=credential.secret, max_range_size=4 * 1024) + self.fsc = ShareServiceClient(url, credential=credential.secret, max_range_size=4 * 1024) self.bsc = BlobServiceClient(blob_url, credential=credential.secret) - self.source_container_name = self.get_resource_name('sourceshare') - self.share_name = self.get_resource_name('utshare') + self.source_container_name = self.get_resource_name("sourceshare") + self.share_name = self.get_resource_name("utshare") self.short_byte_data = self.get_random_bytes(1024) remote_url = self.account_url(rmt_account, "file") @@ -88,15 +93,16 @@ async def _create_source_blob(self): except: pass blob_client = self.bsc.get_blob_client(self.source_container_name, self.get_resource_name(TEST_BLOB_PREFIX)) - await blob_client.upload_blob(b'abcdefghijklmnop' * 32, overwrite=True) + await blob_client.upload_blob(b"abcdefghijklmnop" * 32, overwrite=True) return blob_client async def _setup_share(self, storage_account_name, storage_account_key, remote=False): share_name = self.remote_share_name if remote else self.share_name async with ShareServiceClient( - self.account_url(storage_account_name, "file"), - credential=storage_account_key.secret, - max_range_size=4 * 1024) as fsc: + self.account_url(storage_account_name, "file"), + credential=storage_account_key.secret, + max_range_size=4 * 1024, + ) as fsc: if not self.is_playback(): try: await fsc.create_share(share_name) @@ -127,7 +133,7 @@ async def _get_file_client(self, storage_account_name, storage_account_key): return file_client async def _create_remote_share(self): - self.remote_share_name = self.get_resource_name('remoteshare') + self.remote_share_name = self.get_resource_name("remoteshare") remote_share = self.fsc2.get_share_client(self.remote_share_name) try: await remote_share.create_share() @@ -137,7 +143,7 @@ async def _create_remote_share(self): async def _create_remote_file(self, file_data=None): if not file_data: - file_data = b'12345678' * 1024 + file_data = b"12345678" * 1024 source_file_name = self._get_file_reference() remote_share = self.fsc2.get_share_client(self.remote_share_name) remote_file = remote_share.get_file_client(source_file_name) @@ -149,13 +155,13 @@ async def _wait_for_async_copy(self, share_name, file_path): share_client = self.fsc.get_share_client(share_name) file_client = share_client.get_file_client(file_path) properties = await file_client.get_file_properties() - while properties.copy.status != 'success': + while properties.copy.status != "success": count = count + 1 if count > 15: - pytest.fail('Timed out waiting for async copy to complete.') + pytest.fail("Timed out waiting for async copy to complete.") self.sleep(6) properties = await file_client.get_file_properties() - assert properties.copy.status == 'success' + assert properties.copy.status == "success" async def assertFileEqual(self, file_client, expected_data, **kwargs): content = await file_client.download_file(**kwargs) @@ -188,7 +194,7 @@ async def test_make_file_url(self, **kwargs): res = file_client.url # Assert - assert res == ('https://' + storage_account_name + '.file.core.windows.net/vhds/vhd_dir/my.vhd') + assert res == ("https://" + storage_account_name + ".file.core.windows.net/vhds/vhd_dir/my.vhd") @FileSharePreparer() @recorded_by_proxy_async @@ -204,7 +210,7 @@ async def test_make_file_url_no_directory(self, **kwargs): res = file_client.url # Assert - assert res == ('https://' + storage_account_name + '.file.core.windows.net/vhds/my.vhd') + assert res == ("https://" + storage_account_name + ".file.core.windows.net/vhds/my.vhd") @FileSharePreparer() @recorded_by_proxy_async @@ -213,7 +219,7 @@ async def test_make_file_url_with_protocol(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - url = self.account_url(storage_account_name, "file").replace('https', 'http') + url = self.account_url(storage_account_name, "file").replace("https", "http") fsc = ShareServiceClient(url, credential=storage_account_key.secret) share = fsc.get_share_client("vhds") file_client = share.get_file_client("vhd_dir/my.vhd") @@ -222,7 +228,7 @@ async def test_make_file_url_with_protocol(self, **kwargs): res = file_client.url # Assert - assert res == ('http://' + storage_account_name + '.file.core.windows.net/vhds/vhd_dir/my.vhd') + assert res == ("http://" + storage_account_name + ".file.core.windows.net/vhds/vhd_dir/my.vhd") @FileSharePreparer() @recorded_by_proxy_async @@ -232,20 +238,19 @@ async def test_make_file_url_with_sas(self, **kwargs): self._setup(storage_account_name, storage_account_key) # cspell:disable-next-line - sas = ('?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&' - 'sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D') + sas = "?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name="vhds", file_path="vhd_dir/my.vhd", - credential=sas + credential=sas, ) # Act res = file_client.url # Assert - assert res == ('https://' + storage_account_name + '.file.core.windows.net/vhds/vhd_dir/my.vhd{}'.format(sas)) + assert res == ("https://" + storage_account_name + ".file.core.windows.net/vhds/vhd_dir/my.vhd{}".format(sas)) @FileSharePreparer() @recorded_by_proxy_async @@ -260,7 +265,8 @@ async def test_exists(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) as file_client: + credential=storage_account_key.secret, + ) as file_client: # Act / Assert assert not await file_client.exists() @@ -281,7 +287,8 @@ async def test_create_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) as file_client: + credential=storage_account_key.secret, + ) as file_client: # Act resp = await file_client.create_file(1024) @@ -289,8 +296,8 @@ async def test_create_file(self, **kwargs): # Assert props = await file_client.get_file_properties() assert props is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] @FileSharePreparer() @recorded_by_proxy_async @@ -303,19 +310,20 @@ async def test_create_file_with_oauth(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) file_name = self._get_file_reference() async with ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=file_name, - credential=token_credential, - token_intent=TEST_INTENT) as file_client: + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name, + credential=token_credential, + token_intent=TEST_INTENT, + ) as file_client: # Act resp = await file_client.create_file(1024) # Assert props = await file_client.get_file_properties() assert props is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] @FileSharePreparer() @recorded_by_proxy_async @@ -334,7 +342,7 @@ async def test_create_file_with_oauth_no_token_intent(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=token_credential + credential=token_credential, ) @FileSharePreparer() @@ -347,20 +355,21 @@ async def test_create_file_with_trailing_dot(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) file_name = self._get_file_reference() async with ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=file_name + '.', - credential=storage_account_key.secret, - allow_trailing_dot=True) as file_client: + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + ".", + credential=storage_account_key.secret, + allow_trailing_dot=True, + ) as file_client: # Act resp = await file_client.create_file(1024) # Assert props = await file_client.get_file_properties() assert props is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] - assert props.name == file_name + '.' + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -374,9 +383,10 @@ async def test_create_file_with_trailing_dot_false(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=False) + allow_trailing_dot=False, + ) # Act resp = await file_client.create_file(1024) @@ -385,9 +395,10 @@ async def test_create_file_with_trailing_dot_false(self, **kwargs): file_client_dotted = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=False) + allow_trailing_dot=False, + ) # create file client without dot file_client_no_dot = ShareFileClient( @@ -395,17 +406,18 @@ async def test_create_file_with_trailing_dot_false(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - allow_trailing_dot=False) + allow_trailing_dot=False, + ) props = await file_client.get_file_properties() props_dotted = await file_client_dotted.get_file_properties() props_no_dot = await file_client_no_dot.get_file_properties() # Assert - assert props.name == file_name + '.' - assert props.path == file_name + '.' - assert props_dotted.name == file_name + '.' - assert props_dotted.path == file_name + '.' + assert props.name == file_name + "." + assert props.path == file_name + "." + assert props_dotted.name == file_name + "." + assert props_dotted.path == file_name + "." assert props_no_dot.name == file_name assert props_no_dot.path == file_name @@ -417,13 +429,14 @@ async def test_create_file_with_metadata(self, **kwargs): self._setup(storage_account_name, storage_account_key) await self._setup_share(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} file_name = self._get_file_reference() async with ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) as file_client: + credential=storage_account_key.secret, + ) as file_client: # Act resp = await file_client.create_file(1024, metadata=metadata) @@ -431,8 +444,8 @@ async def test_create_file_with_metadata(self, **kwargs): # Assert props = await file_client.get_file_properties() assert props is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] assert props.metadata == metadata @FileSharePreparer() @@ -443,24 +456,25 @@ async def test_create_file_with_metadata_with_trailing_dot(self, **kwargs): self._setup(storage_account_name, storage_account_key) await self._setup_share(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} file_name = self._get_file_reference() async with ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=file_name + '.', - credential=storage_account_key.secret, - allow_trailing_dot=True) as file_client: + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + ".", + credential=storage_account_key.secret, + allow_trailing_dot=True, + ) as file_client: # Act resp = await file_client.create_file(1024, metadata=metadata) # Assert props = await file_client.get_file_properties() assert props is not None - assert props.etag == resp['etag'] - assert props.last_modified == resp['last_modified'] + assert props.etag == resp["etag"] + assert props.last_modified == resp["last_modified"] assert props.metadata == metadata - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -486,6 +500,46 @@ async def test_create_file_with_invalid_file_permission(self, **kwargs): with pytest.raises(HttpResponseError): await file_name.create_file(1024, file_permission="abcde") + @FileSharePreparer() + @recorded_by_proxy_async + async def test_create_file_semantics(self, **kwargs): + storage_account_name = kwargs.pop("storage_account_name") + storage_account_key = kwargs.pop("storage_account_key") + + self._setup(storage_account_name, storage_account_key) + await self._setup_share(storage_account_name, storage_account_key) + file_name = self._get_file_reference() + + file1 = ShareFileClient( + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + "file1", + credential=storage_account_key.secret, + ) + await file1.create_file(1024, file_property_semantics=None) + props = await file1.get_file_properties() + assert props is not None + + file2 = ShareFileClient( + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + "file2", + credential=storage_account_key.secret, + ) + await file2.create_file(1024, file_property_semantics="New") + props = await file2.get_file_properties() + assert props is not None + + file3 = ShareFileClient( + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + "file2", + credential=storage_account_key.secret, + ) + await file3.create_file(1024, file_property_semantics="Restore", file_permission=TEST_FILE_PERMISSIONS) + props = await file3.get_file_properties() + assert props is not None + @FileSharePreparer() @recorded_by_proxy_async async def test_create_file_with_lease(self, **kwargs): @@ -496,7 +550,7 @@ async def test_create_file_with_lease(self, **kwargs): file_client = await self._get_file_client(storage_account_name, storage_account_key) await file_client.create_file(1024) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") resp = await file_client.create_file(1024, lease=lease) assert resp is not None @@ -522,10 +576,11 @@ async def test_create_file_with_lease_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) await file_client.create_file(1024) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") resp = await file_client.create_file(1024, lease=lease) assert resp is not None @@ -546,9 +601,9 @@ async def test_create_file_with_changed_lease(self, **kwargs): file_client = await self._get_file_client(storage_account_name, storage_account_key) await file_client.create_file(1024) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") old_lease_id = lease.id - await lease.change('44444444-3333-2222-1111-000000000000') + await lease.change("44444444-3333-2222-1111-000000000000") # use the old lease id to create file will throw exception. with pytest.raises(HttpResponseError): @@ -574,12 +629,13 @@ async def test_create_file_with_changed_lease_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) await file_client.create_file(1024) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") old_lease_id = lease.id - await lease.change('44444444-3333-2222-1111-000000000000') + await lease.change("44444444-3333-2222-1111-000000000000") # use the old lease id to create file will throw exception. with pytest.raises(HttpResponseError): @@ -602,14 +658,15 @@ async def test_lease_operations_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await file_client.create_file(1024) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") old_lease_id = lease.id - await lease.change('44444444-3333-2222-1111-000000000000') + await lease.change("44444444-3333-2222-1111-000000000000") # use the old lease id to create file will throw exception. with pytest.raises(HttpResponseError): @@ -627,7 +684,7 @@ async def test_lease_operations_trailing_dot(self, **kwargs): # Assert assert resp is not None - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -660,7 +717,8 @@ async def test_create_file_set_smb_properties(self, **kwargs): file_attributes = NTFSAttributes(read_only=True, archive=True) file_creation_time = file_last_write_time = file_change_time = datetime( - 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc) + 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc + ) # Act await file_client.create_file( @@ -668,7 +726,8 @@ async def test_create_file_set_smb_properties(self, **kwargs): file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, - file_change_time=file_change_time) + file_change_time=file_change_time, + ) file_properties = await file_client.get_file_properties() # Assert @@ -676,8 +735,8 @@ async def test_create_file_set_smb_properties(self, **kwargs): assert file_creation_time == file_properties.creation_time assert file_last_write_time == file_properties.last_write_time assert file_change_time == file_properties.change_time - assert 'ReadOnly' in file_properties.file_attributes - assert 'Archive' in file_properties.file_attributes + assert "ReadOnly" in file_properties.file_attributes + assert "Archive" in file_properties.file_attributes @FileSharePreparer() @recorded_by_proxy_async @@ -733,7 +792,8 @@ async def test_file_not_exists(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path="missingdir/" + file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act with pytest.raises(ResourceNotFoundError): @@ -757,7 +817,8 @@ async def test_file_exists_with_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) props = await snapshot_client.get_file_properties() # Assert @@ -782,7 +843,8 @@ async def test_file_not_exists_with_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Assert with pytest.raises(ResourceNotFoundError): @@ -812,7 +874,7 @@ async def test_resize_file_with_lease(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_client = await self._create_file(storage_account_name, storage_account_key) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act with pytest.raises(HttpResponseError): @@ -833,9 +895,7 @@ async def test_set_file_properties(self, **kwargs): file_client = await self._create_file(storage_account_name, storage_account_key) # Act - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") resp = await file_client.set_http_headers(content_settings=content_settings) # Assert @@ -869,14 +929,10 @@ async def test_set_datetime_all_ms_precision(self, **kwargs): ] # Act / Assert - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") for date1, date2 in zip(date_times[::2], date_times[1::2]): await file_client.set_http_headers( - content_settings=content_settings, - file_creation_time=date1, - file_last_write_time=date2 + content_settings=content_settings, file_creation_time=date1, file_last_write_time=date2 ) @FileSharePreparer() @@ -889,17 +945,16 @@ async def test_set_file_properties_trailing_dot(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) file_name = self._get_file_reference() file_client = ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=file_name + '.', - credential=storage_account_key.secret, - allow_trailing_dot=True) + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name + ".", + credential=storage_account_key.secret, + allow_trailing_dot=True, + ) await file_client.create_file(1024) # Act - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") resp = await file_client.set_http_headers(content_settings=content_settings) # Assert @@ -909,7 +964,7 @@ async def test_set_file_properties_trailing_dot(self, **kwargs): assert properties.last_write_time is not None assert properties.creation_time is not None assert properties.permission_key is not None - assert properties.name == file_name + '.' + assert properties.name == file_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -921,9 +976,7 @@ async def test_set_file_properties_with_file_permission(self, **kwargs): file_client = await self._create_file(storage_account_name, storage_account_key) properties_on_creation = await file_client.get_file_properties() - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") ntfs_attributes = NTFSAttributes(archive=True, temporary=True) last_write_time = properties_on_creation.last_write_time + timedelta(hours=3) @@ -936,7 +989,7 @@ async def test_set_file_properties_with_file_permission(self, **kwargs): file_attributes=ntfs_attributes, file_last_write_time=last_write_time, file_creation_time=creation_time, - file_change_time=change_time + file_change_time=change_time, ) # Assert @@ -960,14 +1013,15 @@ async def test_set_file_properties_with_oauth(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) file_name = self._get_file_reference() async with ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=file_name, - credential=token_credential, - token_intent=TEST_INTENT) as file_client: + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name, + credential=token_credential, + token_intent=TEST_INTENT, + ) as file_client: # Act await file_client.create_file(1024) - content_settings = ContentSettings(content_language='spanish', content_disposition='inline') + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") resp = await file_client.set_http_headers(content_settings=content_settings) # Assert @@ -1005,11 +1059,12 @@ async def test_get_file_properties_with_oauth(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) file_name = self._get_file_reference() async with ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=file_name, - credential=token_credential, - token_intent=TEST_INTENT) as file_client: + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name, + credential=token_credential, + token_intent=TEST_INTENT, + ) as file_client: # Act resp = await file_client.create_file(1024) @@ -1031,9 +1086,10 @@ async def test_get_file_properties_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await file_client.create_file(1024) # Ensure allow_trailing_dot=True is enforced properly by attempting to connect without trailing dot @@ -1041,7 +1097,8 @@ async def test_get_file_properties_trailing_dot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) with pytest.raises(HttpResponseError): await file_client_no_dot.get_file_properties() @@ -1059,11 +1116,11 @@ async def test_get_file_properties_with_invalid_lease_fails(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_client = await self._create_file(storage_account_name, storage_account_key) - await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act with pytest.raises(HttpResponseError): - await file_client.get_file_properties(lease='44444444-3333-2222-1111-000000000000') + await file_client.get_file_properties(lease="44444444-3333-2222-1111-000000000000") # get properties on a leased file will succeed properties = await file_client.get_file_properties() @@ -1096,7 +1153,8 @@ async def test_get_file_properties_with_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) snapshot_props = await snapshot_client.get_file_properties() # Assert assert file_props is not None @@ -1122,7 +1180,8 @@ async def test_get_file_metadata_with_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) metadata2 = {"test100": "foo100", "test200": "bar200"} await file_client.set_file_metadata(metadata2) @@ -1147,7 +1206,8 @@ async def test_get_file_properties_with_non_existing_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act with pytest.raises(ResourceNotFoundError): @@ -1178,7 +1238,7 @@ async def test_set_file_metadata_with_upper_case(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42', 'UP': 'UPval'} + metadata = {"hello": "world", "number": "42", "UP": "UPval"} file_client = await self._create_file(storage_account_name, storage_account_key) # Act @@ -1188,10 +1248,10 @@ async def test_set_file_metadata_with_upper_case(self, **kwargs): props = await file_client.get_file_properties() md = props.metadata assert 3 == len(md) - assert md['hello'] == 'world' - assert md['number'] == '42' - assert md['UP'] == 'UPval' - assert not 'up' in md + assert md["hello"] == "world" + assert md["number"] == "42" + assert md["UP"] == "UPval" + assert not "up" in md @FileSharePreparer() @recorded_by_proxy_async @@ -1204,12 +1264,13 @@ async def test_set_file_metadata_with_oauth(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) file_name = self._get_file_reference() async with ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=file_name, - credential=token_credential, - token_intent=TEST_INTENT) as file_client: - metadata = {'hello': 'world', 'number': '42', 'UP': 'UPval'} + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name, + credential=token_credential, + token_intent=TEST_INTENT, + ) as file_client: + metadata = {"hello": "world", "number": "42", "UP": "UPval"} # Act resp = await file_client.create_file(1024) @@ -1219,10 +1280,10 @@ async def test_set_file_metadata_with_oauth(self, **kwargs): props = await file_client.get_file_properties() md = props.metadata assert 3 == len(md) - assert md['hello'] == 'world' - assert md['number'] == '42' - assert md['UP'] == 'UPval' - assert not 'up' in md + assert md["hello"] == "world" + assert md["number"] == "42" + assert md["UP"] == "UPval" + assert not "up" in md @FileSharePreparer() @recorded_by_proxy_async @@ -1232,7 +1293,7 @@ async def test_break_lease_with_broken_period_fails(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_client = await self._create_file(storage_account_name, storage_account_key) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Assert assert lease is not None @@ -1246,10 +1307,10 @@ async def test_set_file_metadata_with_broken_lease(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42', 'UP': 'UPval'} + metadata = {"hello": "world", "number": "42", "UP": "UPval"} file_client = await self._create_file(storage_account_name, storage_account_key) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") with pytest.raises(HttpResponseError): await file_client.set_file_metadata(metadata) @@ -1258,11 +1319,11 @@ async def test_set_file_metadata_with_broken_lease(self, **kwargs): # Act # lease is broken, set metadata doesn't require a lease - await file_client.set_file_metadata({'hello': 'world'}) + await file_client.set_file_metadata({"hello": "world"}) props = await file_client.get_file_properties() # Assert assert 1 == len(props.metadata) - assert props.metadata['hello'] == 'world' + assert props.metadata["hello"] == "world" # Act await file_client.acquire_lease(lease_id=lease_id_to_be_broken) @@ -1271,10 +1332,10 @@ async def test_set_file_metadata_with_broken_lease(self, **kwargs): props = await file_client.get_file_properties() md = props.metadata assert 3 == len(md) - assert md['hello'] == 'world' - assert md['number'] == '42' - assert md['UP'] == 'UPval' - assert not 'up' in md + assert md["hello"] == "world" + assert md["number"] == "42" + assert md["UP"] == "UPval" + assert not "up" in md @FileSharePreparer() @recorded_by_proxy_async @@ -1307,7 +1368,8 @@ async def test_delete_file_with_existing_file_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act resp = await file_client.create_file(1024) @@ -1329,9 +1391,10 @@ async def test_delete_file_with_existing_file_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await file_client.create_file(1024) # Act @@ -1353,7 +1416,8 @@ async def test_delete_file_with_non_existing_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act with pytest.raises(ResourceNotFoundError): @@ -1371,7 +1435,7 @@ async def test_update_range(self, **kwargs): file_client = await self._create_file(storage_account_name, storage_account_key) # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 await file_client.upload_range(data, offset=0, length=512) # Assert @@ -1392,13 +1456,14 @@ async def test_update_range_with_oauth(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1', + file_path="file1", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act await file_client.upload_file(self.short_byte_data) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 await file_client.upload_range(data, offset=0, length=512) # Assert @@ -1419,13 +1484,14 @@ async def test_update_range_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await file_client.upload_file(self.short_byte_data) # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 await file_client.upload_range(data, offset=0, length=512) props = await file_client.get_file_properties() @@ -1434,7 +1500,7 @@ async def test_update_range_trailing_dot(self, **kwargs): content = await content.readall() assert data == content[:512] assert self.short_byte_data[512:] == content[512:] - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -1444,10 +1510,10 @@ async def test_update_range_with_lease(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_client = await self._create_file(storage_account_name, storage_account_key) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 with pytest.raises(HttpResponseError): await file_client.upload_range(data, offset=0, length=512) await file_client.upload_range(data, offset=0, length=512, lease=lease) @@ -1468,7 +1534,7 @@ async def test_update_range_with_md5(self, **kwargs): file_client = await self._create_file(storage_account_name, storage_account_key) # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 await file_client.upload_range(data, offset=0, length=512, validate_content=True) # Assert @@ -1484,7 +1550,7 @@ async def test_update_range_last_written_mode_now(self, **kwargs): current_last_write_time = (await file_client.get_file_properties()).last_write_time # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 await file_client.upload_range(data, offset=0, length=512, file_last_write_mode="Now") # Assert @@ -1502,7 +1568,7 @@ async def test_update_range_last_written_mode_preserve(self, **kwargs): current_last_write_time = (await file_client.get_file_properties()).last_write_time # Act - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 await file_client.upload_range(data, offset=0, length=512, file_last_write_mode="Preserve") # Assert @@ -1516,18 +1582,14 @@ async def test_update_range_from_file_url_when_source_file_does_not_have_enough_ storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_name = 'testfile1' + source_file_name = "testfile1" source_file_client = await self._create_file( - storage_account_name, - storage_account_key, - file_name=source_file_name + storage_account_name, storage_account_key, file_name=source_file_name ) - destination_file_name = 'filetoupdate' + destination_file_name = "filetoupdate" destination_file_client = await self._create_file( - storage_account_name, - storage_account_key, - file_name=destination_file_name + storage_account_name, storage_account_key, file_name=destination_file_name ) # generate SAS for the source file @@ -1538,10 +1600,10 @@ async def test_update_range_from_file_url_when_source_file_does_not_have_enough_ source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1) + expiry=datetime.utcnow() + timedelta(hours=1), ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act with pytest.raises(HttpResponseError): @@ -1555,20 +1617,16 @@ async def test_update_range_from_file_url(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_name = 'testfile' + source_file_name = "testfile" source_file_client = await self._create_file( - storage_account_name, - storage_account_key, - file_name=source_file_name + storage_account_name, storage_account_key, file_name=source_file_name ) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 await source_file_client.upload_range(data, offset=0, length=512) - destination_file_name = 'filetoupdate' + destination_file_name = "filetoupdate" destination_file_client = await self._create_empty_file( - storage_account_name, - storage_account_key, - file_name=destination_file_name + storage_account_name, storage_account_key, file_name=destination_file_name ) # generate SAS for the source file @@ -1579,9 +1637,10 @@ async def test_update_range_from_file_url(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act await destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0) @@ -1591,8 +1650,8 @@ async def test_update_range_from_file_url(self, **kwargs): file_content = await destination_file_client.download_file(offset=0, length=512) file_content = await file_content.readall() assert 1 == len(file_ranges) - assert 0 == file_ranges[0].get('start') - assert 511 == file_ranges[0].get('end') + assert 0 == file_ranges[0].get("start") + assert 511 == file_ranges[0].get("end") assert data == file_content @FileSharePreparer() @@ -1604,18 +1663,22 @@ async def test_update_range_from_file_url_with_oauth(self, **kwargs): self._setup(storage_account_name, storage_account_key) source_blob_client = await self._create_source_blob() access_token = await self.get_credential(ShareServiceClient, is_async=True).get_token( - "https://storage.azure.com/.default") + "https://storage.azure.com/.default" + ) token = "Bearer {}".format(access_token.token) - destination_file_name = 'filetoupdate' + destination_file_name = "filetoupdate" destination_file_client = await self._create_empty_file( - storage_account_name, storage_account_key, file_name=destination_file_name) + storage_account_name, storage_account_key, file_name=destination_file_name + ) with pytest.raises(HttpResponseError): await destination_file_client.upload_range_from_url( - source_blob_client.url, offset=0, length=512, source_offset=0) + source_blob_client.url, offset=0, length=512, source_offset=0 + ) await destination_file_client.upload_range_from_url( - source_blob_client.url, offset=0, length=512, source_offset=0, source_authorization=token) + source_blob_client.url, offset=0, length=512, source_offset=0, source_authorization=token + ) @FileSharePreparer() @recorded_by_proxy_async @@ -1624,22 +1687,18 @@ async def test_update_range_from_file_url_with_lease(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_name = 'testfile' + source_file_name = "testfile" source_file_client = await self._create_file( - storage_account_name, - storage_account_key, - file_name=source_file_name + storage_account_name, storage_account_key, file_name=source_file_name ) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 await source_file_client.upload_range(data, offset=0, length=512) - destination_file_name = 'filetoupdate' + destination_file_name = "filetoupdate" destination_file_client = await self._create_empty_file( - storage_account_name, - storage_account_key, - file_name=destination_file_name + storage_account_name, storage_account_key, file_name=destination_file_name ) - lease = await destination_file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await destination_file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # generate SAS for the source file sas_token_for_source_file = self.generate_sas( @@ -1649,14 +1708,16 @@ async def test_update_range_from_file_url_with_lease(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act with pytest.raises(HttpResponseError): await destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0) - await destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0, - lease=lease) + await destination_file_client.upload_range_from_url( + source_file_url, offset=0, length=512, source_offset=0, lease=lease + ) # Assert # To make sure the range of the file is actually updated @@ -1664,8 +1725,8 @@ async def test_update_range_from_file_url_with_lease(self, **kwargs): file_content = await destination_file_client.download_file(offset=0, length=512) file_content = await file_content.readall() assert 1 == len(file_ranges) - assert 0 == file_ranges[0].get('start') - assert 511 == file_ranges[0].get('end') + assert 0 == file_ranges[0].get("start") + assert 511 == file_ranges[0].get("end") assert data == file_content @FileSharePreparer() @@ -1675,24 +1736,18 @@ async def test_update_big_range_from_file_url(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_name = 'testfile1' + source_file_name = "testfile1" end = 1048575 source_file_client = await self._create_empty_file( - storage_account_name, - storage_account_key, - file_name=source_file_name, - file_size=1024 * 1024 + storage_account_name, storage_account_key, file_name=source_file_name, file_size=1024 * 1024 ) - data = b'abcdefghijklmnop' * 65536 - await source_file_client.upload_range(data, offset=0, length=end+1) + data = b"abcdefghijklmnop" * 65536 + await source_file_client.upload_range(data, offset=0, length=end + 1) - destination_file_name = 'filetoupdate1' + destination_file_name = "filetoupdate1" destination_file_client = await self._create_empty_file( - storage_account_name, - storage_account_key, - file_name=destination_file_name, - file_size=1024 * 1024 + storage_account_name, storage_account_key, file_name=destination_file_name, file_size=1024 * 1024 ) # generate SAS for the source file @@ -1703,12 +1758,13 @@ async def test_update_big_range_from_file_url(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act - await destination_file_client.upload_range_from_url(source_file_url, offset=0, length=end+1, source_offset=0) + await destination_file_client.upload_range_from_url(source_file_url, offset=0, length=end + 1, source_offset=0) # Assert # To make sure the range of the file is actually updated @@ -1716,8 +1772,8 @@ async def test_update_big_range_from_file_url(self, **kwargs): file_content = await destination_file_client.download_file(offset=0, length=end + 1) file_content = await file_content.readall() assert 1 == len(file_ranges) - assert 0 == file_ranges[0].get('start') - assert end == file_ranges[0].get('end') + assert 0 == file_ranges[0].get("start") + assert end == file_ranges[0].get("end") assert data == file_content @FileSharePreparer() @@ -1727,14 +1783,13 @@ async def test_update_range_from_file_url_last_written_mode_now(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_client = await self._create_file(storage_account_name, storage_account_key, file_name='testfile') - data = b'abcdefghijklmnop' * 32 + source_file_client = await self._create_file(storage_account_name, storage_account_key, file_name="testfile") + data = b"abcdefghijklmnop" * 32 await source_file_client.upload_range(data, offset=0, length=512) destination_file_client = await self._create_empty_file( - storage_account_name, - storage_account_key, - file_name='filetoupdate') + storage_account_name, storage_account_key, file_name="filetoupdate" + ) current_last_write_time = (await destination_file_client.get_file_properties()).last_write_time # generate SAS for the source file @@ -1745,13 +1800,15 @@ async def test_update_range_from_file_url_last_written_mode_now(self, **kwargs): source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act - await destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0, - file_last_write_mode="Now") + await destination_file_client.upload_range_from_url( + source_file_url, offset=0, length=512, source_offset=0, file_last_write_mode="Now" + ) # Assert new_last_write_time = (await destination_file_client.get_file_properties()).last_write_time @@ -1764,14 +1821,13 @@ async def test_update_range_from_file_url_last_written_mode_preserve(self, **kwa storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file_client = await self._create_file(storage_account_name, storage_account_key, file_name='testfile') - data = b'abcdefghijklmnop' * 32 + source_file_client = await self._create_file(storage_account_name, storage_account_key, file_name="testfile") + data = b"abcdefghijklmnop" * 32 await source_file_client.upload_range(data, offset=0, length=512) destination_file_client = await self._create_empty_file( - storage_account_name, - storage_account_key, - file_name='filetoupdate') + storage_account_name, storage_account_key, file_name="filetoupdate" + ) current_last_write_time = (await destination_file_client.get_file_properties()).last_write_time # generate SAS for the source file @@ -1782,13 +1838,15 @@ async def test_update_range_from_file_url_last_written_mode_preserve(self, **kwa source_file_client.file_path, source_file_client.credential.account_key, FileSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(hours=1)) + expiry=datetime.utcnow() + timedelta(hours=1), + ) - source_file_url = source_file_client.url + '?' + sas_token_for_source_file + source_file_url = source_file_client.url + "?" + sas_token_for_source_file # Act - await destination_file_client.upload_range_from_url(source_file_url, offset=0, length=512, source_offset=0, - file_last_write_mode="Preserve") + await destination_file_client.upload_range_from_url( + source_file_url, offset=0, length=512, source_offset=0, file_last_write_mode="Preserve" + ) # Assert new_last_write_time = (await destination_file_client.get_file_properties()).last_write_time @@ -1809,7 +1867,7 @@ async def test_clear_range(self, **kwargs): # Assert content = await file_client.download_file() content = await content.readall() - assert b'\x00' * 512 == content[:512] + assert b"\x00" * 512 == content[:512] assert self.short_byte_data[512:] == content[512:] @FileSharePreparer() @@ -1824,9 +1882,10 @@ async def test_clear_range_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await file_client.upload_file(self.short_byte_data) # Act @@ -1836,9 +1895,9 @@ async def test_clear_range_trailing_dot(self, **kwargs): # Assert content = await file_client.download_file() content = await content.readall() - assert b'\x00' * 512 == content[:512] + assert b"\x00" * 512 == content[:512] assert self.short_byte_data[512:] == content[512:] - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -1850,10 +1909,10 @@ async def test_update_file_unicode(self, **kwargs): file_client = await self._create_file(storage_account_name, storage_account_key) # Act - data = 'abcdefghijklmnop' * 32 + data = "abcdefghijklmnop" * 32 await file_client.upload_range(data, offset=0, length=512) - encoded = data.encode('utf-8') + encoded = data.encode("utf-8") # Assert content = await file_client.download_file() @@ -1876,7 +1935,8 @@ async def test_list_ranges_none(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.create_file(1024) # Act @@ -1898,9 +1958,10 @@ async def test_list_ranges_none_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await file_client.create_file(1024) # Act @@ -1910,7 +1971,7 @@ async def test_list_ranges_none_trailing_dot(self, **kwargs): # Assert assert ranges is not None assert len(ranges) == 0 - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -1925,13 +1986,14 @@ async def test_list_ranges_none_with_invalid_lease_fails(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.create_file(1024) - await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act with pytest.raises(HttpResponseError): - await file_client.get_ranges(lease='44444444-3333-2222-1111-000000000000') + await file_client.get_ranges(lease="44444444-3333-2222-1111-000000000000") # Get ranges on a leased file will succeed without provide the lease ranges = await file_client.get_ranges() @@ -1953,7 +2015,8 @@ async def test_list_ranges_diff(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.create_file(2048) share_client = self.fsc.get_share_client(self.share_name) @@ -1965,7 +2028,7 @@ async def test_list_ranges_diff(self, **kwargs): await file_client.clear_range(offset=512, length=512) ranges1, cleared1 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot1) - ranges2, cleared2 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot2['snapshot']) + ranges2, cleared2 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot2["snapshot"]) # Assert assert ranges1 is not None @@ -1973,20 +2036,20 @@ async def test_list_ranges_diff(self, **kwargs): assert len(ranges1) == 2 assert isinstance(cleared1, list) assert len(cleared1) == 1 - assert ranges1[0]['start'] == 0 - assert ranges1[0]['end'] == 511 - assert cleared1[0]['start'] == 512 - assert cleared1[0]['end'] == 1023 - assert ranges1[1]['start'] == 1024 - assert ranges1[1]['end'] == 1535 + assert ranges1[0]["start"] == 0 + assert ranges1[0]["end"] == 511 + assert cleared1[0]["start"] == 512 + assert cleared1[0]["end"] == 1023 + assert ranges1[1]["start"] == 1024 + assert ranges1[1]["end"] == 1535 assert ranges2 is not None assert isinstance(ranges2, list) assert len(ranges2) == 0 assert isinstance(cleared2, list) assert len(cleared2) == 1 - assert cleared2[0]['start'] == 512 - assert cleared2[0]['end'] == 1023 + assert cleared2[0]["start"] == 512 + assert cleared2[0]["end"] == 1023 @FileSharePreparer() @recorded_by_proxy_async @@ -2003,7 +2066,8 @@ async def test_list_ranges_diff_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) await file_client.create_file(2048) share_client = self.fsc.get_share_client(self.share_name) @@ -2015,7 +2079,7 @@ async def test_list_ranges_diff_with_oauth(self, **kwargs): await file_client.clear_range(offset=512, length=512) ranges1, cleared1 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot1) - ranges2, cleared2 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot2['snapshot']) + ranges2, cleared2 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot2["snapshot"]) # Assert assert ranges1 is not None @@ -2023,20 +2087,20 @@ async def test_list_ranges_diff_with_oauth(self, **kwargs): assert len(ranges1) == 2 assert isinstance(cleared1, list) assert len(cleared1) == 1 - assert ranges1[0]['start'] == 0 - assert ranges1[0]['end'] == 511 - assert cleared1[0]['start'] == 512 - assert cleared1[0]['end'] == 1023 - assert ranges1[1]['start'] == 1024 - assert ranges1[1]['end'] == 1535 + assert ranges1[0]["start"] == 0 + assert ranges1[0]["end"] == 511 + assert cleared1[0]["start"] == 512 + assert cleared1[0]["end"] == 1023 + assert ranges1[1]["start"] == 1024 + assert ranges1[1]["end"] == 1535 assert ranges2 is not None assert isinstance(ranges2, list) assert len(ranges2) == 0 assert isinstance(cleared2, list) assert len(cleared2) == 1 - assert cleared2[0]['start'] == 512 - assert cleared2[0]['end'] == 1023 + assert cleared2[0]["start"] == 512 + assert cleared2[0]["end"] == 1023 @FileSharePreparer() @recorded_by_proxy_async @@ -2050,9 +2114,10 @@ async def test_list_ranges_diff_trailing_dot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, - allow_trailing_dot=True) + allow_trailing_dot=True, + ) await file_client.create_file(2048) share_client = self.fsc.get_share_client(self.share_name) @@ -2064,7 +2129,7 @@ async def test_list_ranges_diff_trailing_dot(self, **kwargs): await file_client.clear_range(offset=512, length=512) ranges1, cleared1 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot1) - ranges2, cleared2 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot2['snapshot']) + ranges2, cleared2 = await file_client.get_ranges_diff(previous_sharesnapshot=snapshot2["snapshot"]) props = await file_client.get_file_properties() # Assert @@ -2073,22 +2138,22 @@ async def test_list_ranges_diff_trailing_dot(self, **kwargs): assert len(ranges1) == 2 assert isinstance(cleared1, list) assert len(cleared1) == 1 - assert ranges1[0]['start'] == 0 - assert ranges1[0]['end'] == 511 - assert cleared1[0]['start'] == 512 - assert cleared1[0]['end'] == 1023 - assert ranges1[1]['start'] == 1024 - assert ranges1[1]['end'] == 1535 + assert ranges1[0]["start"] == 0 + assert ranges1[0]["end"] == 511 + assert cleared1[0]["start"] == 512 + assert cleared1[0]["end"] == 1023 + assert ranges1[1]["start"] == 1024 + assert ranges1[1]["end"] == 1535 assert ranges2 is not None assert isinstance(ranges2, list) assert len(ranges2) == 0 assert isinstance(cleared2, list) assert len(cleared2) == 1 - assert cleared2[0]['start'] == 512 - assert cleared2[0]['end'] == 1023 + assert cleared2[0]["start"] == 512 + assert cleared2[0]["end"] == 1023 - assert props.name == file_name + '.' + assert props.name == file_name + "." @FileSharePreparer() @recorded_by_proxy_async @@ -2103,7 +2168,8 @@ async def test_list_ranges_diff_support_rename(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.create_file(2048) share_client = self.fsc.get_share_client(self.share_name) @@ -2114,7 +2180,7 @@ async def test_list_ranges_diff_support_rename(self, **kwargs): previous_snapshot = await share_client.create_snapshot() await file_client.clear_range(offset=512, length=512) await file_client.upload_range(data2, offset=512, length=512) - file_client = await file_client.rename_file(file_name + 'renamed') + file_client = await file_client.rename_file(file_name + "renamed") # Assert with pytest.raises(ResourceExistsError): @@ -2122,16 +2188,15 @@ async def test_list_ranges_diff_support_rename(self, **kwargs): with pytest.raises(ResourceExistsError): await file_client.get_ranges_diff(previous_sharesnapshot=previous_snapshot, include_renames=False) ranges, cleared = await file_client.get_ranges_diff( - previous_sharesnapshot=previous_snapshot, - include_renames=True + previous_sharesnapshot=previous_snapshot, include_renames=True ) assert ranges is not None assert isinstance(ranges, list) assert len(ranges) == 1 assert isinstance(cleared, list) assert len(cleared) == 0 - assert ranges[0]['start'] == 512 - assert ranges[0]['end'] == 1023 + assert ranges[0]["start"] == 512 + assert ranges[0]["end"] == 1023 @FileSharePreparer() @recorded_by_proxy_async @@ -2146,10 +2211,11 @@ async def test_list_ranges_2(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.create_file(2048) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 resp1 = await file_client.upload_range(data, offset=0, length=512) resp2 = await file_client.upload_range(data, offset=1024, length=512) @@ -2159,10 +2225,10 @@ async def test_list_ranges_2(self, **kwargs): # Assert assert ranges is not None assert len(ranges) == 2 - assert ranges[0]['start'] == 0 - assert ranges[0]['end'] == 511 - assert ranges[1]['start'] == 1024 - assert ranges[1]['end'] == 1535 + assert ranges[0]["start"] == 0 + assert ranges[0]["end"] == 511 + assert ranges[1]["start"] == 1024 + assert ranges[1]["end"] == 1535 @FileSharePreparer() @recorded_by_proxy_async @@ -2177,7 +2243,8 @@ async def test_list_ranges_none_from_snapshot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.create_file(1024) share_client = self.fsc.get_share_client(self.share_name) @@ -2187,7 +2254,8 @@ async def test_list_ranges_none_from_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.delete_file() @@ -2213,7 +2281,8 @@ async def test_list_ranges_none_from_snapshot_with_oauth(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) await file_client.create_file(1024) share_client = self.fsc.get_share_client(self.share_name) @@ -2224,7 +2293,8 @@ async def test_list_ranges_none_from_snapshot_with_oauth(self, **kwargs): file_path=file_client.file_name, snapshot=snapshot, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) await file_client.delete_file() @@ -2248,9 +2318,10 @@ async def test_list_ranges_2_from_snapshot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.create_file(2048) - data = b'abcdefghijklmnop' * 32 + data = b"abcdefghijklmnop" * 32 resp1 = await file_client.upload_range(data, offset=0, length=512) resp2 = await file_client.upload_range(data, offset=1024, length=512) @@ -2261,7 +2332,8 @@ async def test_list_ranges_2_from_snapshot(self, **kwargs): share_name=self.share_name, file_path=file_client.file_name, snapshot=snapshot, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.delete_file() @@ -2271,10 +2343,10 @@ async def test_list_ranges_2_from_snapshot(self, **kwargs): # Assert assert ranges is not None assert len(ranges) == 2 - assert ranges[0]['start'] == 0 - assert ranges[0]['end'] == 511 - assert ranges[1]['start'] == 1024 - assert ranges[1]['end'] == 1535 + assert ranges[0]["start"] == 0 + assert ranges[0]["end"] == 511 + assert ranges[1]["start"] == 1024 + assert ranges[1]["end"] == 1535 @FileSharePreparer() @recorded_by_proxy_async @@ -2287,16 +2359,17 @@ async def test_copy_file_with_existing_file(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) # Act copy = await file_client.start_copy_from_url(source_client.url) # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = await file_client.download_file() content = await copy_file.readall() @@ -2314,17 +2387,18 @@ async def test_copy_file_with_existing_file_oauth(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', + file_path="file1copy", credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) # Act copy = await file_client.start_copy_from_url(source_client.url) # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = await file_client.download_file() content = await copy_file.readall() @@ -2342,19 +2416,21 @@ async def test_copy_file_with_existing_file_trailing_dot(self, **kwargs): source_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=file_name + '.', + file_path=file_name + ".", credential=storage_account_key.secret, allow_trailing_dot=True, - allow_source_trailing_dot=True) + allow_source_trailing_dot=True, + ) await source_client.upload_file(self.short_byte_data) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy.', + file_path="file1copy.", credential=storage_account_key.secret, allow_trailing_dot=True, - allow_source_trailing_dot=True) + allow_source_trailing_dot=True, + ) @FileSharePreparer() @recorded_by_proxy_async @@ -2367,10 +2443,11 @@ async def test_copy_existing_file_with_lease(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) await file_client.create_file(1024) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act with pytest.raises(HttpResponseError): @@ -2380,8 +2457,8 @@ async def test_copy_existing_file_with_lease(self, **kwargs): # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = await file_client.download_file() content = await copy_file.readall() @@ -2398,8 +2475,9 @@ async def test_copy_file_ignore_readonly(self, **kwargs): dest_file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) file_attributes = NTFSAttributes(read_only=True) await dest_file.create_file(1024, file_attributes=file_attributes) @@ -2412,8 +2490,8 @@ async def test_copy_file_ignore_readonly(self, **kwargs): # Assert assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = await dest_file.download_file() content = await copy_file.readall() @@ -2430,8 +2508,9 @@ async def test_copy_file_with_specifying_acl_copy_behavior_attributes(self, **kw file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) source_props = await source_client.get_file_properties() file_creation_time = source_props.creation_time - timedelta(hours=1) @@ -2453,15 +2532,15 @@ async def test_copy_file_with_specifying_acl_copy_behavior_attributes(self, **kw # Assert dest_prop = await file_client.get_file_properties() # to make sure the attributes are the same as the set ones - assert file_creation_time == dest_prop['creation_time'] - assert file_last_write_time == dest_prop['last_write_time'] - assert file_change_time == dest_prop['change_time'] - assert 'Temporary' in dest_prop['file_attributes'] - assert 'NoScrubData' in dest_prop['file_attributes'] + assert file_creation_time == dest_prop["creation_time"] + assert file_last_write_time == dest_prop["last_write_time"] + assert file_change_time == dest_prop["change_time"] + assert "Temporary" in dest_prop["file_attributes"] + assert "NoScrubData" in dest_prop["file_attributes"] assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = await file_client.download_file() content = await copy_file.readall() @@ -2479,23 +2558,21 @@ async def test_copy_file_with_specifying_acl_and_attributes_from_source(self, ** file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='file1copy', - credential=storage_account_key.secret) + file_path="file1copy", + credential=storage_account_key.secret, + ) # Act - copy = await file_client.start_copy_from_url( - source_client.url, - permission_key='source' - ) + copy = await file_client.start_copy_from_url(source_client.url, permission_key="source") # Assert dest_prop = await file_client.get_file_properties() # to make sure the acl is copied from source - assert source_prop['permission_key'] == dest_prop['permission_key'] + assert source_prop["permission_key"] == dest_prop["permission_key"] assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None copy_file = await file_client.download_file() content = await copy_file.readall() @@ -2513,19 +2590,20 @@ async def test_copy_file_async_private_file_async(self, **kwargs): storage_account_name, storage_account_key, secondary_storage_account_name, - secondary_storage_account_key.secret + secondary_storage_account_key.secret, ) await self._setup_share(storage_account_name, storage_account_key) await self._create_remote_share() source_file = await self._create_remote_file() # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) with pytest.raises(HttpResponseError) as e: await file_client.start_copy_from_url(source_file.url) @@ -2545,9 +2623,9 @@ async def test_copy_file_async_private_file_with_sas_async(self, **kwargs): storage_account_name, storage_account_key, secondary_storage_account_name, - secondary_storage_account_key.secret + secondary_storage_account_key.secret, ) - data = b'12345678' * 1024 + data = b"12345678" * 1024 await self._create_remote_share() source_file = await self._create_remote_file(file_data=data) sas_token = self.generate_sas( @@ -2559,20 +2637,21 @@ async def test_copy_file_async_private_file_with_sas_async(self, **kwargs): permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), ) - source_url = source_file.url + '?' + sas_token + source_url = source_file.url + "?" + sas_token # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" await self._setup_share(storage_account_name, storage_account_key) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) copy_resp = await file_client.start_copy_from_url(source_url) # Assert - assert copy_resp['copy_status'] in ['success', 'pending'] + assert copy_resp["copy_status"] in ["success", "pending"] await self._wait_for_async_copy(self.share_name, target_file_name) content = await file_client.download_file() @@ -2591,9 +2670,9 @@ async def test_abort_copy_file_async(self, **kwargs): storage_account_name, storage_account_key, secondary_storage_account_name, - secondary_storage_account_key.secret + secondary_storage_account_key.secret, ) - data = b'12345678' * 1024 * 1024 + data = b"12345678" * 1024 * 1024 await self._setup_share(storage_account_name, storage_account_key) await self._create_remote_share() source_file = await self._create_remote_file(file_data=data) @@ -2606,24 +2685,25 @@ async def test_abort_copy_file_async(self, **kwargs): permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), ) - source_url = source_file.url + '?' + sas_token + source_url = source_file.url + "?" + sas_token # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) copy_resp = await file_client.start_copy_from_url(source_url) - assert copy_resp['copy_status'] == 'pending' + assert copy_resp["copy_status"] == "pending" await file_client.abort_copy(copy_resp) # Assert target_file = await file_client.download_file() content = await target_file.readall() - assert content == b'' - assert target_file.properties.copy.status == 'aborted' + assert content == b"" + assert target_file.properties.copy.status == "aborted" @pytest.mark.live_test_only @FileSharePreparer() @@ -2638,9 +2718,9 @@ async def test_abort_copy_file_async_with_oauth(self, **kwargs): storage_account_name, storage_account_key, secondary_storage_account_name, - secondary_storage_account_key.secret + secondary_storage_account_key.secret, ) - data = b'12345678' * 1024 * 1024 + data = b"12345678" * 1024 * 1024 await self._setup_share(storage_account_name, storage_account_key) await self._create_remote_share() source_file = await self._create_remote_file(file_data=data) @@ -2653,25 +2733,26 @@ async def test_abort_copy_file_async_with_oauth(self, **kwargs): permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), ) - source_url = source_file.url + '?' + sas_token + source_url = source_file.url + "?" + sas_token # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, credential=token_credential, - token_intent=TEST_INTENT) + token_intent=TEST_INTENT, + ) copy_resp = await file_client.start_copy_from_url(source_url) - assert copy_resp['copy_status'] == 'pending' + assert copy_resp["copy_status"] == "pending" await file_client.abort_copy(copy_resp) # Assert target_file = await file_client.download_file() content = await target_file.readall() - assert content == b'' - assert target_file.properties.copy.status == 'aborted' + assert content == b"" + assert target_file.properties.copy.status == "aborted" @FileSharePreparer() @recorded_by_proxy_async @@ -2683,19 +2764,20 @@ async def test_abort_copy_file_with_synchronous_copy_fails(self, **kwargs): source_file = await self._create_file(storage_account_name, storage_account_key) # Act - target_file_name = 'targetfile' + target_file_name = "targetfile" file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=target_file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) copy_resp = await file_client.start_copy_from_url(source_file.url) with pytest.raises(HttpResponseError): await file_client.abort_copy(copy_resp) # Assert - assert copy_resp['copy_status'] == 'success' + assert copy_resp["copy_status"] == "success" @FileSharePreparer() @recorded_by_proxy_async @@ -2704,21 +2786,22 @@ async def test_unicode_get_file_unicode_name(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_name = '啊齄丂狛狜' + file_name = "啊齄丂狛狜" await self._setup_share(storage_account_name, storage_account_key) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) - await file_client.upload_file(b'hello world') + credential=storage_account_key.secret, + ) + await file_client.upload_file(b"hello world") # Act content = await file_client.download_file() content = await content.readall() # Assert - assert content == b'hello world' + assert content == b"hello world" @FileSharePreparer() @recorded_by_proxy_async @@ -2727,31 +2810,32 @@ async def test_unicode_get_file_unicode_name_with_lease(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_name = '啊齄丂狛狜' + file_name = "啊齄丂狛狜" await self._setup_share(storage_account_name, storage_account_key) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.create_file(1024) - lease = await file_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await file_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") with pytest.raises(HttpResponseError): - await file_client.upload_file(b'hello world') + await file_client.upload_file(b"hello world") - await file_client.upload_file(b'hello world', lease=lease) + await file_client.upload_file(b"hello world", lease=lease) # Act # download the file with a wrong lease id will fail with pytest.raises(HttpResponseError): - await file_client.upload_file(b'hello world', lease='44444444-3333-2222-1111-000000000000') + await file_client.upload_file(b"hello world", lease="44444444-3333-2222-1111-000000000000") content = await file_client.download_file() content = await content.readall() # Assert - assert content == b'hello world' + assert content == b"hello world" @FileSharePreparer() @recorded_by_proxy_async @@ -2766,10 +2850,11 @@ async def test_file_unicode_data(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act - data = 'hello world啊齄丂狛狜'.encode('utf-8') + data = "hello world啊齄丂狛狜".encode("utf-8") await file_client.upload_file(data) # Assert @@ -2787,7 +2872,7 @@ async def test_file_unicode_data_and_file_attributes(self, **kwargs): file_client = await self._get_file_client(storage_account_name, storage_account_key) # Act - data = 'hello world啊齄丂狛狜'.encode('utf-8') + data = "hello world啊齄丂狛狜".encode("utf-8") await file_client.upload_file(data, file_attributes=NTFSAttributes(temporary=True)) # Assert @@ -2795,7 +2880,7 @@ async def test_file_unicode_data_and_file_attributes(self, **kwargs): transformed_content = await content.readall() properties = await file_client.get_file_properties() assert transformed_content == data - assert 'Temporary' in properties.file_attributes + assert "Temporary" in properties.file_attributes @FileSharePreparer() @recorded_by_proxy_async @@ -2804,22 +2889,7 @@ async def test_unicode_get_file_binary_data(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - base64_data = ( - 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0' - 'xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYm' - 'ZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm' - '5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM' - '0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gI' - 'GCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNz' - 's/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRob' - 'HB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2h' - 'pamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tb' - 'a3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECA' - 'wQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9Q' - 'UVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2' - 'en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6' - 'uvs7e7v8PHy8/T19vf4+fr7/P3+/w==' - ) + base64_data = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==" binary_data = base64.b64decode(base64_data) await self._setup_share(storage_account_name, storage_account_key) @@ -2828,7 +2898,8 @@ async def test_unicode_get_file_binary_data(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) await file_client.upload_file(binary_data) # Act @@ -2853,13 +2924,15 @@ async def test_create_file_from_bytes_with_progress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act progress = [] + def callback(response): - current = response.context['upload_stream_current'] - total = response.context['data_stream_total'] + current = response.context["upload_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -2884,13 +2957,14 @@ async def test_create_file_from_bytes_with_index(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act response = await file_client.upload_file(data[index:], max_concurrency=2) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert await self.assertFileEqual(file_client, data[1024:]) @@ -2912,16 +2986,17 @@ async def test_create_file_from_bytes_with_index_and_count(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act response = await file_client.upload_file(data[index:], length=count, max_concurrency=2) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert - await self.assertFileEqual(file_client, data[index:index + count]) + await self.assertFileEqual(file_client, data[index : index + count]) @pytest.mark.live_test_only @FileSharePreparer() @@ -2938,7 +3013,8 @@ async def test_create_file_from_path(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -2946,8 +3022,8 @@ async def test_create_file_from_path(self, **kwargs): temp_file.seek(0) response = await file_client.upload_file(temp_file, max_concurrency=2) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert await self.assertFileEqual(file_client, data) @@ -2967,13 +3043,15 @@ async def test_create_file_from_path_with_progress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act progress = [] + def callback(response): - current = response.context['upload_stream_current'] - total = response.context['data_stream_total'] + current = response.context["upload_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -2982,8 +3060,8 @@ def callback(response): temp_file.seek(0) response = await file_client.upload_file(temp_file, max_concurrency=2, raw_response_hook=callback) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert await self.assertFileEqual(file_client, data) @@ -3004,7 +3082,8 @@ async def test_create_file_from_stream(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_size = len(data) @@ -3013,8 +3092,8 @@ async def test_create_file_from_stream(self, **kwargs): temp_file.seek(0) response = await file_client.upload_file(temp_file, max_concurrency=2) assert isinstance(response, dict) - assert 'last_modified' in response - assert 'etag' in response + assert "last_modified" in response + assert "etag" in response # Assert await self.assertFileEqual(file_client, data[:file_size]) @@ -3034,7 +3113,8 @@ async def test_create_file_from_stream_non_seekable(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_size = len(data) @@ -3062,13 +3142,15 @@ async def test_create_file_from_stream_with_progress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act progress = [] + def callback(response): - current = response.context['upload_stream_current'] - total = response.context['data_stream_total'] + current = response.context["upload_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -3097,7 +3179,8 @@ async def test_create_file_from_stream_truncated(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act file_size = len(data) - 512 @@ -3124,13 +3207,15 @@ async def test_create_file_from_stream_with_progress_truncated(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act progress = [] + def callback(response): - current = response.context['upload_stream_current'] - total = response.context['data_stream_total'] + current = response.context["upload_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -3153,7 +3238,7 @@ async def test_create_file_from_async_generator(self, **kwargs): self._setup(storage_account_name, storage_account_key) await self._setup_share(storage_account_name, storage_account_key) file_name = self._get_file_reference() - data = b'Hello Async World!' + data = b"Hello Async World!" async def data_generator(): for _ in range(3): @@ -3164,14 +3249,15 @@ async def data_generator(): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret) + credential=storage_account_key.secret, + ) # Act - file_size = len(data*3) + file_size = len(data * 3) await file_client.upload_file(data_generator(), length=file_size) # Assert - await self.assertFileEqual(file_client, data*3) + await self.assertFileEqual(file_client, data * 3) @FileSharePreparer() @recorded_by_proxy_async @@ -3182,14 +3268,15 @@ async def test_create_file_from_text(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_name = self._get_file_reference() await self._setup_share(storage_account_name, storage_account_key) - text = 'hello 啊齄丂狛狜 world' - data = text.encode('utf-8') + text = "hello 啊齄丂狛狜 world" + data = text.encode("utf-8") file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act await file_client.upload_file(text) @@ -3206,17 +3293,18 @@ async def test_create_file_from_text_with_encoding(self, **kwargs): self._setup(storage_account_name, storage_account_key) file_name = self._get_file_reference() await self._setup_share(storage_account_name, storage_account_key) - text = 'hello 啊齄丂狛狜 world' - data = text.encode('utf-16') + text = "hello 啊齄丂狛狜 world" + data = text.encode("utf-16") file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act - await file_client.upload_file(text, encoding='UTF-16') + await file_client.upload_file(text, encoding="UTF-16") # Assert await self.assertFileEqual(file_client, data) @@ -3232,13 +3320,14 @@ async def test_create_file_from_text_chunked_upload(self, **kwargs): file_name = self._get_file_reference() await self._setup_share(storage_account_name, storage_account_key) data = self.get_random_text_data(LARGE_FILE_SIZE) - encoded_data = data.encode('utf-8') + encoded_data = data.encode("utf-8") file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act await file_client.upload_file(data) @@ -3262,7 +3351,8 @@ async def test_create_file_with_md5_small(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act await file_client.upload_file(data, validate_content=True) @@ -3284,7 +3374,8 @@ async def test_create_file_with_md5_large(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) # Act await file_client.upload_file(data, validate_content=True, max_concurrency=2) @@ -3306,9 +3397,10 @@ async def test_create_file_progress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=1024) + max_range_size=1024, + ) - data = b'a' * 5 * 1024 + data = b"a" * 5 * 1024 progress = ProgressTracker(len(data), 1024) # Act @@ -3333,9 +3425,10 @@ async def test_create_file_progress_parallel(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=1024) + max_range_size=1024, + ) - data = b'a' * 5 * 1024 + data = b"a" * 5 * 1024 progress = ProgressTracker(len(data), 1024) # Act @@ -3368,7 +3461,8 @@ async def test_sas_access_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=token) + credential=token, + ) content = await file_client.download_file() content = await content.readall() @@ -3380,19 +3474,19 @@ async def test_sas_access_file(self, **kwargs): async def test_sas_signed_identifier(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - variables = kwargs.pop('variables', {}) + variables = kwargs.pop("variables", {}) self._setup(storage_account_name, storage_account_key) file_client = await self._create_file(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) access_policy = AccessPolicy() - start_time = self.get_datetime_variable(variables, 'start_time', datetime.utcnow() - timedelta(hours=1)) - expiry_time = self.get_datetime_variable(variables, 'expiry_time', datetime.utcnow() + timedelta(hours=1)) + start_time = self.get_datetime_variable(variables, "start_time", datetime.utcnow() - timedelta(hours=1)) + expiry_time = self.get_datetime_variable(variables, "expiry_time", datetime.utcnow() + timedelta(hours=1)) access_policy.start = start_time access_policy.expiry = expiry_time access_policy.permission = FileSasPermissions(read=True) - identifiers = {'testid': access_policy} + identifiers = {"testid": access_policy} await share_client.set_share_access_policy(identifiers) token = self.generate_sas( @@ -3401,12 +3495,11 @@ async def test_sas_signed_identifier(self, **kwargs): file_client.share_name, file_client.file_path, file_client.credential.account_key, - policy_id='testid') + policy_id="testid", + ) # Act - sas_file = ShareFileClient.from_file_url( - file_client.url, - credential=token) + sas_file = ShareFileClient.from_file_url(file_client.url, credential=token) content = await file_client.download_file() content = await content.readall() @@ -3438,9 +3531,10 @@ async def test_account_sas(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=token) + credential=token, + ) - response = requests.get(file_client.url, timeout=15) + response = requests.get(file_client.url) # Assert assert response.ok @@ -3468,7 +3562,8 @@ async def test_account_sas_credential(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=AzureSasCredential(token)) + credential=AzureSasCredential(token), + ) properties = await file_client.get_file_properties() @@ -3481,7 +3576,6 @@ async def test_azure_named_key_credential_access(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - self._setup(storage_account_name, storage_account_key) file_client = await self._create_file(storage_account_name, storage_account_key) named_key = AzureNamedKeyCredential(storage_account_name, storage_account_key.secret) @@ -3491,7 +3585,8 @@ async def test_azure_named_key_credential_access(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=named_key) + credential=named_key, + ) properties = await file_client.get_file_properties() @@ -3507,7 +3602,8 @@ async def test_account_sas_raises_if_sas_already_in_uri(self, **kwargs): self.account_url(storage_account_name, "file") + "?sig=foo", share_name="foo", file_path="foo", - credential=AzureSasCredential("?foo=bar")) + credential=AzureSasCredential("?foo=bar"), + ) @pytest.mark.live_test_only @FileSharePreparer() @@ -3532,8 +3628,9 @@ async def test_shared_read_access_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=token) - response = requests.get(file_client.url, timeout=15) + credential=token, + ) + response = requests.get(file_client.url) # Assert assert response.ok @@ -3555,11 +3652,11 @@ async def test_shared_read_access_file_with_content_query_params(self, **kwargs) file_client.credential.account_key, permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), - cache_control='no-cache', - content_disposition='inline', - content_encoding='utf-8', - content_language='fr', - content_type='text', + cache_control="no-cache", + content_disposition="inline", + content_encoding="utf-8", + content_language="fr", + content_type="text", ) # Act @@ -3567,16 +3664,17 @@ async def test_shared_read_access_file_with_content_query_params(self, **kwargs) self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client.file_name, - credential=token) - response = requests.get(file_client.url, timeout=15) + credential=token, + ) + response = requests.get(file_client.url) # Assert assert self.short_byte_data == response.content - assert response.headers['cache-control'] == 'no-cache' - assert response.headers['content-disposition'] == 'inline' - assert response.headers['content-encoding'] == 'utf-8' - assert response.headers['content-language'] == 'fr' - assert response.headers['content-type'] == 'text' + assert response.headers["cache-control"] == "no-cache" + assert response.headers["content-disposition"] == "inline" + assert response.headers["content-encoding"] == "utf-8" + assert response.headers["content-language"] == "fr" + assert response.headers["content-type"] == "text" @pytest.mark.live_test_only @FileSharePreparer() @@ -3585,7 +3683,7 @@ async def test_shared_write_access_file(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - updated_data = b'updated file data' + updated_data = b"updated file data" file_client_admin = await self._create_file(storage_account_name, storage_account_key) token = self.generate_sas( generate_file_sas, @@ -3600,17 +3698,18 @@ async def test_shared_write_access_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client_admin.file_name, - credential=token) + credential=token, + ) # Act - headers = {'x-ms-range': 'bytes=0-16', 'x-ms-write': 'update'} - response = requests.put(file_client.url + '&comp=range', headers=headers, data=updated_data, timeout=15) + headers = {"x-ms-range": "bytes=0-16", "x-ms-write": "update"} + response = requests.put(file_client.url + "&comp=range", headers=headers, data=updated_data) # Assert assert response.ok file_content = await file_client_admin.download_file() file_content = await file_content.readall() - assert updated_data == file_content[:len(updated_data)] + assert updated_data == file_content[: len(updated_data)] @pytest.mark.live_test_only @FileSharePreparer() @@ -3633,10 +3732,11 @@ async def test_shared_delete_access_file(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_client_admin.file_name, - credential=token) + credential=token, + ) # Act - response = requests.delete(file_client.url, timeout=15) + response = requests.delete(file_client.url) # Assert assert response.ok @@ -3650,13 +3750,13 @@ async def test_rename_file(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file = await self._create_file(storage_account_name, storage_account_key, 'file1') + source_file = await self._create_file(storage_account_name, storage_account_key, "file1") # Act - new_file = await source_file.rename_file('file2') + new_file = await source_file.rename_file("file2") # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = await new_file.get_file_properties() assert props is not None @@ -3670,20 +3770,20 @@ async def test_rename_file_with_oauth(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) file_name = self._get_file_reference() async with ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=file_name, - credential=storage_account_key.secret) as file_client: + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=file_name, + credential=storage_account_key.secret, + ) as file_client: # Act resp = await file_client.create_file(1024) - new_file = await file_client.rename_file('file2') + new_file = await file_client.rename_file("file2") # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = await new_file.get_file_properties() assert props is not None - @FileSharePreparer() @recorded_by_proxy_async async def test_rename_file_different_directory(self, **kwargs): @@ -3694,15 +3794,15 @@ async def test_rename_file_different_directory(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_directory = await share_client.create_directory('dir1') - dest_directory = await share_client.create_directory('dir2') - source_file = await source_directory.upload_file('file1', self.short_byte_data) + source_directory = await share_client.create_directory("dir1") + dest_directory = await share_client.create_directory("dir2") + source_file = await source_directory.upload_file("file1", self.short_byte_data) # Act - new_file = await source_file.rename_file(dest_directory.directory_path + '/' + source_file.file_name) + new_file = await source_file.rename_file(dest_directory.directory_path + "/" + source_file.file_name) # Assert - assert 'dir2' in new_file.file_path + assert "dir2" in new_file.file_path props = await new_file.get_file_properties() assert props is not None @@ -3716,9 +3816,9 @@ async def test_rename_file_ignore_readonly(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_file = share_client.get_file_client('file1') + source_file = share_client.get_file_client("file1") await source_file.create_file(1024) - dest_file = share_client.get_file_client('file2') + dest_file = share_client.get_file_client("file2") file_attributes = NTFSAttributes(read_only=True) await dest_file.create_file(1024, file_attributes=file_attributes) @@ -3727,7 +3827,7 @@ async def test_rename_file_ignore_readonly(self, **kwargs): new_file = await source_file.rename_file(dest_file.file_name, overwrite=True, ignore_read_only=True) # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = await new_file.get_file_properties() assert props is not None @@ -3742,11 +3842,11 @@ async def test_rename_file_file_permission(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) file_permission_key = await share_client.create_permission_for_share(TEST_FILE_PERMISSIONS) - source_file = share_client.get_file_client('file1') + source_file = share_client.get_file_client("file1") await source_file.create_file(1024) # Act - new_file = await source_file.rename_file('file2', file_permission=TEST_FILE_PERMISSIONS) + new_file = await source_file.rename_file("file2", file_permission=TEST_FILE_PERMISSIONS) # Assert props = await new_file.get_file_properties() @@ -3763,14 +3863,14 @@ async def test_rename_file_preserve_permission(self, **kwargs): await self._setup_share(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_file = share_client.get_file_client('file1') + source_file = share_client.get_file_client("file1") await source_file.create_file(1024, file_permission=TEST_FILE_PERMISSIONS) source_props = await source_file.get_file_properties() source_permission_key = source_props.permission_key # Act - new_file = await source_file.rename_file('file2', file_permission='preserve') + new_file = await source_file.rename_file("file2", file_permission="preserve") # Assert props = await new_file.get_file_properties() @@ -3784,7 +3884,7 @@ async def test_rename_file_smb_properties(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file = await self._create_file(storage_account_name, storage_account_key, 'file1') + source_file = await self._create_file(storage_account_name, storage_account_key, "file1") file_attributes = NTFSAttributes(read_only=True, archive=True) file_creation_time = datetime(2022, 1, 26, 10, 9, 30, 500000, tzinfo=timezone.utc) @@ -3793,16 +3893,17 @@ async def test_rename_file_smb_properties(self, **kwargs): # Act new_file = await source_file.rename_file( - 'file2', + "file2", file_attributes=file_attributes, file_creation_time=file_creation_time, file_last_write_time=file_last_write_time, - file_change_time=file_change_time) + file_change_time=file_change_time, + ) # Assert props = await new_file.get_file_properties() assert props is not None - assert str(file_attributes).replace(' ', '') == props.file_attributes.replace(' ', ''), props.file_attributes + assert str(file_attributes), props.file_attributes.replace(" " == "") assert file_creation_time == props.creation_time assert file_last_write_time == props.last_write_time assert file_change_time == props.change_time @@ -3814,13 +3915,11 @@ async def test_rename_file_content_type(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - source_file = await self._create_file(storage_account_name, storage_account_key, 'file1') - content_type = 'text/plain' + source_file = await self._create_file(storage_account_name, storage_account_key, "file1") + content_type = "text/plain" # Act - new_file = await source_file.rename_file( - 'file2', - content_type=content_type) + new_file = await source_file.rename_file("file2", content_type=content_type) # Assert props = await new_file.get_file_properties() @@ -3835,20 +3934,18 @@ async def test_rename_file_with_lease(self, **kwargs): self._setup(storage_account_name, storage_account_key) - source_file = await self._create_file(storage_account_name, storage_account_key, 'file1') - dest_file = await self._create_file(storage_account_name, storage_account_key, 'file2') - source_lease = await source_file.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') - dest_lease = await dest_file.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + source_file = await self._create_file(storage_account_name, storage_account_key, "file1") + dest_file = await self._create_file(storage_account_name, storage_account_key, "file2") + source_lease = await source_file.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") + dest_lease = await dest_file.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act new_file = await source_file.rename_file( - dest_file.file_name, - overwrite=True, - source_lease=source_lease, - destination_lease=dest_lease) + dest_file.file_name, overwrite=True, source_lease=source_lease, destination_lease=dest_lease + ) # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = await new_file.get_file_properties() assert props is not None @@ -3868,19 +3965,19 @@ async def test_rename_file_share_sas(self, **kwargs): share_client.share_name, share_client.credential.account_key, expiry=datetime.utcnow() + timedelta(hours=1), - permission=ShareSasPermissions(read=True, write=True)) + permission=ShareSasPermissions(read=True, write=True), + ) source_file = ShareFileClient( - self.account_url(storage_account_name, 'file'), - share_client.share_name, 'file1', - credential=token) + self.account_url(storage_account_name, "file"), share_client.share_name, "file1", credential=token + ) await source_file.create_file(1024) # Act - new_file = await source_file.rename_file('file2' + '?' + token) + new_file = await source_file.rename_file("file2" + "?" + token) # Assert - assert 'file2' == new_file.file_name + assert "file2" == new_file.file_name props = await new_file.get_file_properties() assert props is not None @@ -3898,7 +3995,7 @@ async def test_storage_account_audience_file_client(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) await file_client.create_file(1024) @@ -3913,7 +4010,7 @@ async def test_storage_account_audience_file_client(self, **kwargs): file_path=file_name, credential=token_credential, token_intent=TEST_INTENT, - audience=f'https://{storage_account_name}.file.core.windows.net' + audience=f"https://{storage_account_name}.file.core.windows.net", ) # Assert @@ -3934,7 +4031,7 @@ async def test_bad_audience_file_client(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) await file_client.create_file(1024) @@ -3949,7 +4046,7 @@ async def test_bad_audience_file_client(self, **kwargs): file_path=file_name, credential=token_credential, token_intent=TEST_INTENT, - audience='https://badaudience.file.core.windows.net' + audience=f"https://badaudience.file.core.windows.net", ) # Assert @@ -3964,18 +4061,20 @@ async def test_file_permission_format(self, **kwargs): self._setup(storage_account_name, storage_account_key) await self._setup_share(storage_account_name, storage_account_key) share_client = self.fsc.get_share_client(self.share_name) - source_file = share_client.get_file_client('file1') - user_given_permission_sddl = ("O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" - "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" - "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL") - user_given_permission_binary = ("AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" - "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" - "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=") + source_file = share_client.get_file_client("file1") + user_given_permission_sddl = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL" + ) + user_given_permission_binary = ( + "AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" + "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" + "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=" + ) await source_file.create_file( - 1024, - file_permission=user_given_permission_binary, - file_permission_format="binary" + 1024, file_permission=user_given_permission_binary, file_permission_format="binary" ) props = await source_file.get_file_properties() @@ -3983,28 +4082,22 @@ async def test_file_permission_format(self, **kwargs): assert props.permission_key is not None new_file = await source_file.rename_file( - 'file2', - file_permission=user_given_permission_binary, - file_permission_format="binary" + "file2", file_permission=user_given_permission_binary, file_permission_format="binary" ) props = await new_file.get_file_properties() assert props is not None assert props.permission_key is not None server_returned_permission = await share_client.get_permission_for_share( - props.permission_key, - file_permission_format="binary" + props.permission_key, file_permission_format="binary" ) assert server_returned_permission == user_given_permission_binary - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline' - ) + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") await new_file.set_http_headers( content_settings=content_settings, file_permission=user_given_permission_binary, - file_permission_format="binary" + file_permission_format="binary", ) props = await new_file.get_file_properties() assert props is not None @@ -4013,8 +4106,7 @@ async def test_file_permission_format(self, **kwargs): assert props.content_settings.content_disposition == content_settings.content_disposition server_returned_permission = await share_client.get_permission_for_share( - props.permission_key, - file_permission_format="sddl" + props.permission_key, file_permission_format="sddl" ) assert server_returned_permission == user_given_permission_sddl @@ -4022,17 +4114,15 @@ async def test_file_permission_format(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path='filecopy', - credential=storage_account_key.secret + file_path="filecopy", + credential=storage_account_key.secret, ) copy = await file_client.start_copy_from_url( - new_file.url, - file_permission=user_given_permission_binary, - file_permission_format="binary" + new_file.url, file_permission=user_given_permission_binary, file_permission_format="binary" ) assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None await new_file.delete_file() await file_client.delete_file() @@ -4051,7 +4141,7 @@ async def test_legacy_transport(self, **kwargs): file_path="filemocktransport", credential=storage_account_key.secret, transport=transport, - retry_total=0 + retry_total=0, ) data = await file_client.download_file() @@ -4082,7 +4172,7 @@ async def test_legacy_transport_with_content_validation(self, **kwargs): file_path="filemocktransport", credential=storage_account_key.secret, transport=transport, - retry_total=0 + retry_total=0, ) data = b"Hello Async World!" @@ -4103,23 +4193,16 @@ async def test_upload_range_copy_source_error_and_status_code(self, **kwargs): try: source_file_client = await self._create_file( - storage_account_name, - storage_account_key, - file_name='sourcefile' + storage_account_name, storage_account_key, file_name="sourcefile" ) - await source_file_client.upload_range(b'abcdefghijklmnop' * 32, offset=0, length=512) + await source_file_client.upload_range(b"abcdefghijklmnop" * 32, offset=0, length=512) target_file_client = await self._create_empty_file( - storage_account_name, - storage_account_key, - file_name='targetfile' + storage_account_name, storage_account_key, file_name="targetfile" ) with pytest.raises(HttpResponseError) as e: await target_file_client.upload_range_from_url( - source_file_client.url, - offset=0, - length=512, - source_offset=0 + source_file_client.url, offset=0, length=512, source_offset=0 ) assert e.value.response.headers["x-ms-copy-source-status-code"] == "401" @@ -4141,12 +4224,11 @@ async def test_download_file_decompress(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024 + max_range_size=4 * 1024, ) - compressed_data = (b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xcaH\xcd\xc9\xc9WH+\xca\xcfUH' - b'\xaf\xca,\x00\x00\x00\x00\xff\xff\x03\x00d\xaa\x8e\xb5\x0f\x00\x00\x00') + compressed_data = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xcaH\xcd\xc9\xc9WH+\xca\xcfUH\xaf\xca,\x00\x00\x00\x00\xff\xff\x03\x00d\xaa\x8e\xb5\x0f\x00\x00\x00" decompressed_data = b"hello from gzip" - content_settings = ContentSettings(content_encoding='gzip') + content_settings = ContentSettings(content_encoding="gzip") # Act / Assert await file_client.upload_file(data=compressed_data, content_settings=content_settings) @@ -4170,9 +4252,8 @@ async def test_download_file_no_decompress_chunks(self, **kwargs): max_chunk_get_size=4, max_single_get_size=4, ) - compressed_data = (b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xcaH\xcd\xc9\xc9WH+\xca\xcfUH' - b'\xaf\xca,\x00\x00\x00\x00\xff\xff\x03\x00d\xaa\x8e\xb5\x0f\x00\x00\x00') - content_settings = ContentSettings(content_encoding='gzip') + compressed_data = b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\xff\xcaH\xcd\xc9\xc9WH+\xca\xcfUH\xaf\xca,\x00\x00\x00\x00\xff\xff\x03\x00d\xaa\x8e\xb5\x0f\x00\x00\x00" + content_settings = ContentSettings(content_encoding="gzip") # Act / Assert await file_client.upload_file(data=compressed_data, content_settings=content_settings) @@ -4194,7 +4275,8 @@ async def test_upload_file_with_none_max_concurrency(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) data = b"hello world" @@ -4217,7 +4299,8 @@ async def test_download_file_with_none_max_concurrency(self, **kwargs): share_name=self.share_name, file_path=file_name, credential=storage_account_key.secret, - max_range_size=4 * 1024) + max_range_size=4 * 1024, + ) data = b"hello world" await file_client.upload_file(data) @@ -4242,7 +4325,7 @@ async def test_create_file_semantics(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name + "file1", - credential=storage_account_key + credential=storage_account_key, ) await file1.create_file(1024, file_property_semantics=None) props = await file1.get_file_properties() @@ -4252,7 +4335,7 @@ async def test_create_file_semantics(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name + "file2", - credential=storage_account_key + credential=storage_account_key, ) await file2.create_file(1024, file_property_semantics="New") props = await file2.get_file_properties() @@ -4262,7 +4345,7 @@ async def test_create_file_semantics(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name + "file2", - credential=storage_account_key + credential=storage_account_key, ) await file3.create_file(1024, file_property_semantics="Restore", file_permission=TEST_FILE_PERMISSIONS) props = await file3.get_file_properties() @@ -4282,7 +4365,7 @@ async def test_create_file_with_data(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=file_name + "file", - credential=storage_account_key.secret + credential=storage_account_key.secret, ) size = 1024 data = b"abc" * size diff --git a/sdk/storage/azure-storage-file-share/tests/test_file_client.py b/sdk/storage/azure-storage-file-share/tests/test_file_client.py index 5f2e492f8e8c..880a88d9b093 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file_client.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file_client.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for @@ -7,12 +8,6 @@ import platform import pytest - -from devtools_testutils import recorded_by_proxy -from devtools_testutils.storage import StorageRecordedTestCase -from devtools_testutils.storage.testcase import generate_sas_token -from settings.testcase import FileSharePreparer - from azure.core.exceptions import AzureError from azure.storage.fileshare import ( LocationMode, @@ -23,18 +18,23 @@ VERSION, ) +from devtools_testutils import recorded_by_proxy +from devtools_testutils.storage import StorageRecordedTestCase +from devtools_testutils.storage.testcase import generate_sas_token +from settings.testcase import FileSharePreparer + # ------------------------------------------------------------------------------ SERVICES = { - ShareServiceClient: 'file', - ShareClient: 'file', - ShareDirectoryClient: 'file', - ShareFileClient: 'file', + ShareServiceClient: "file", + ShareClient: "file", + ShareDirectoryClient: "file", + ShareFileClient: "file", } -_CONNECTION_ENDPOINTS = {'file': 'FileEndpoint'} +_CONNECTION_ENDPOINTS = {"file": "FileEndpoint"} -_CONNECTION_ENDPOINTS_SECONDARY = {'file': 'FileSecondaryEndpoint'} +_CONNECTION_ENDPOINTS_SECONDARY = {"file": "FileSecondaryEndpoint"} class TestStorageFileClient(StorageRecordedTestCase): @@ -49,16 +49,25 @@ def _teardown(self, FILE_PATH): os.remove(FILE_PATH) except: pass + # --Helpers----------------------------------------------------------------- - def validate_standard_account_endpoints(self, service, service_type, protocol='https'): + def validate_standard_account_endpoints(self, service, service_type, protocol="https"): assert service is not None assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_endpoint.startswith( - '{}://{}.{}.core.windows.net/'.format(protocol, self.account_name, service_type)) is True - assert service.secondary_endpoint.startswith( - '{}://{}-secondary.{}.core.windows.net/'.format(protocol, self.account_name, service_type)) is True + assert ( + service.primary_endpoint.startswith( + "{}://{}.{}.core.windows.net/".format(protocol, self.account_name, service_type) + ) + is True + ) + assert ( + service.secondary_endpoint.startswith( + "{}://{}-secondary.{}.core.windows.net/".format(protocol, self.account_name, service_type) + ) + is True + ) def validate_ipv6_account_endpoints(self, service, account_name, account_key, primary_endpoint, secondary_endpoint): assert service is not None @@ -80,12 +89,16 @@ def test_create_service_with_key(self, **kwargs): for client, url in SERVICES.items(): # Act service = client( - self.account_url(storage_account_name, "file"), credential=self.account_key.secret, - share_name='foo', directory_path='bar', file_path='baz') + self.account_url(storage_account_name, "file"), + credential=self.account_key.secret, + share_name="foo", + directory_path="bar", + file_path="baz", + ) # Assert self.validate_standard_account_endpoints(service, url) - assert service.scheme == 'https' + assert service.scheme == "https" @FileSharePreparer() def test_create_service_with_sas(self, **kwargs): @@ -97,8 +110,12 @@ def test_create_service_with_sas(self, **kwargs): for service_type in SERVICES: # Act service = service_type( - self.account_url(storage_account_name, "file"), credential=self.sas_token, - share_name='foo', directory_path='bar', file_path='baz') + self.account_url(storage_account_name, "file"), + credential=self.sas_token, + share_name="foo", + directory_path="bar", + file_path="baz", + ) # Assert assert service is not None @@ -117,8 +134,13 @@ def test_create_service_with_token(self, **kwargs): # token credential is available for FileService token_credential = self.get_credential(ShareServiceClient) try: - service_type(self.account_url(storage_account_name, "file"), credential=token_credential, - share_name='foo', directory_path='bar', file_path='baz') + service_type( + self.account_url(storage_account_name, "file"), + credential=token_credential, + share_name="foo", + directory_path="bar", + file_path="baz", + ) except ValueError: pass @@ -128,22 +150,22 @@ def test_create_service_china(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - url = self.account_url(storage_account_name, "file").replace('core.windows.net', 'core.chinacloudapi.cn') + url = self.account_url(storage_account_name, "file").replace("core.windows.net", "core.chinacloudapi.cn") for service_type in SERVICES.items(): # Act service = service_type[0]( - url, credential=self.account_key.secret, - share_name='foo', directory_path='bar', file_path='baz') + url, credential=self.account_key.secret, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service is not None assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_hostname == '{}.{}.core.chinacloudapi.cn'.format( - self.account_name, service_type[1]) - assert service.secondary_hostname == '{}-secondary.{}.core.chinacloudapi.cn'.format( - self.account_name, service_type[1]) + assert service.primary_hostname == "{}.{}.core.chinacloudapi.cn".format(self.account_name, service_type[1]) + assert service.secondary_hostname == "{}-secondary.{}.core.chinacloudapi.cn".format( + self.account_name, service_type[1] + ) @FileSharePreparer() def test_create_service_protocol(self, **kwargs): @@ -151,15 +173,16 @@ def test_create_service_protocol(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - url = self.account_url(storage_account_name, "file").replace('https', 'http') + url = self.account_url(storage_account_name, "file").replace("https", "http") for service_type in SERVICES.items(): # Act service = service_type[0]( - url, credential=self.account_key.secret, share_name='foo', directory_path='bar', file_path='baz') + url, credential=self.account_key.secret, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert - self.validate_standard_account_endpoints(service, service_type[1], protocol='http') - assert service.scheme == 'http' + self.validate_standard_account_endpoints(service, service_type[1], protocol="http") + assert service.scheme == "http" @FileSharePreparer() def test_create_service_empty_key(self, **kwargs): @@ -173,13 +196,15 @@ def test_create_service_empty_key(self, **kwargs): with pytest.raises(ValueError) as e: service_type( self.account_url(storage_account_name, "file"), - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) - assert (str(e.value.args[0]) == - 'You need to provide either an account shared key or SAS token when creating a storage service.') + assert ( + str(e.value.args[0]) + == "You need to provide either an account shared key or SAS token when creating a storage service." + ) @FileSharePreparer() def test_create_service_with_socket_timeout(self, **kwargs): @@ -193,17 +218,17 @@ def test_create_service_with_socket_timeout(self, **kwargs): default_service = service_type[0]( self.account_url(storage_account_name, "file"), credential=self.account_key.secret, - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) service = service_type[0]( self.account_url(storage_account_name, "file"), credential=self.account_key.secret, connection_timeout=22, - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) # Assert @@ -212,7 +237,8 @@ def test_create_service_with_socket_timeout(self, **kwargs): assert default_service._client._client._pipeline._transport.connection_config.timeout in [20, (20, 2000)] @pytest.mark.parametrize( - "account_url, expected_primary, expected_secondary", [ + "account_url, expected_primary, expected_secondary", + [ ( "https://myaccount.file.core.windows.net/", "myaccount.file.core.windows.net", @@ -243,7 +269,7 @@ def test_create_service_with_socket_timeout(self, **kwargs): "myaccount-secondary-ipv6.file.core.windows.net", "myaccount-secondary-ipv6.file.core.windows.net", ), - ] + ], ) @FileSharePreparer() def test_create_service_ipv6(self, account_url, expected_primary, expected_secondary, **kwargs): @@ -252,13 +278,13 @@ def test_create_service_ipv6(self, account_url, expected_primary, expected_secon share_name, directory_path, file_path = "foo", "bar", "baz" - for service_type in SERVICES: + for service_type in SERVICES.keys(): service = service_type( account_url, credential=storage_account_key.secret, share_name=share_name, directory_path=directory_path, - file_path=file_path + file_path=file_path, ) self.validate_ipv6_account_endpoints( service, storage_account_name, storage_account_key.secret, expected_primary, expected_secondary @@ -275,7 +301,7 @@ def test_create_service_ipv6(self, account_url, expected_primary, expected_secon credential=storage_account_key.secret, share_name=share_name, directory_path=directory_path, - file_path=file_path + file_path=file_path, ) self.validate_ipv6_account_endpoints( service, storage_account_name, storage_account_key.secret, expected_primary, expected_secondary @@ -283,7 +309,7 @@ def test_create_service_ipv6(self, account_url, expected_primary, expected_secon service = ShareFileClient.from_file_url( file_url=f"{account_url}/{share_name}/{directory_path}/{file_path}-secondary", - credential=storage_account_key.secret + credential=storage_account_key.secret, ) self.validate_ipv6_account_endpoints( service, storage_account_name, storage_account_key.secret, expected_primary, expected_secondary @@ -293,16 +319,16 @@ def test_create_service_ipv6(self, account_url, expected_primary, expected_secon def test_create_service_ipv6_custom_domain(self): token_credential = self.get_credential(ShareServiceClient) - hostname= "github.com" + hostname = "github.com" account_url = f"https://{hostname}" - for service_type in SERVICES: + for service_type in SERVICES.keys(): service = service_type( account_url, credential=token_credential, share_name="foo", directory_path="bar", file_path="baz", - token_intent="backup" + token_intent="backup", ) assert service is not None assert service.scheme == "https" @@ -319,16 +345,17 @@ def test_create_service_with_connection_string_key(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - conn_string = 'AccountName={};AccountKey={};'.format(self.account_name, self.account_key.secret) + conn_string = "AccountName={};AccountKey={};".format(self.account_name, self.account_key.secret) for service_type in SERVICES.items(): # Act service = service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert self.validate_standard_account_endpoints(service, service_type[1]) - assert service.scheme == 'https' + assert service.scheme == "https" @FileSharePreparer() def test_create_service_with_connection_string_sas(self, **kwargs): @@ -336,12 +363,13 @@ def test_create_service_with_connection_string_sas(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - conn_string = 'AccountName={};SharedAccessSignature={};'.format(self.account_name, self.sas_token) + conn_string = "AccountName={};SharedAccessSignature={};".format(self.account_name, self.sas_token) for service_type in SERVICES.items(): # Act service = service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service is not None @@ -356,28 +384,27 @@ def test_create_service_with_connection_string_endpoint_protocol(self, **kwargs) self._setup(storage_account_name, storage_account_key) conn_string = ( - 'AccountName={};AccountKey={};DefaultEndpointsProtocol=http;EndpointSuffix=core.chinacloudapi.cn;'.format( - self.account_name, - self.account_key.secret + "AccountName={};AccountKey={};DefaultEndpointsProtocol=http;EndpointSuffix=core.chinacloudapi.cn;".format( + self.account_name, self.account_key.secret ) ) for service_type in SERVICES.items(): # Act service = service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service is not None assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_hostname, '{}.{}.core.chinacloudapi.cn'.format(self.account_name, service_type[1]) - assert service.secondary_hostname == '{}-secondary.{}.core.chinacloudapi.cn'.format( - self.account_name, - service_type[1] + assert service.primary_hostname, "{}.{}.core.chinacloudapi.cn".format(self.account_name == service_type[1]) + assert service.secondary_hostname == "{}-secondary.{}.core.chinacloudapi.cn".format( + self.account_name, service_type[1] ) - assert service.scheme == 'http' + assert service.scheme == "http" @FileSharePreparer() def test_create_service_with_connection_string_emulated(self, **kwargs): @@ -386,12 +413,13 @@ def test_create_service_with_connection_string_emulated(self, **kwargs): self._setup(storage_account_name, storage_account_key) for service_type in SERVICES.items(): - conn_string = 'UseDevelopmentStorage=true;' + conn_string = "UseDevelopmentStorage=true;" # Act with pytest.raises(ValueError): service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) @FileSharePreparer() def test_create_service_with_connection_string_fails_if_secondary_without_primary(self, **kwargs): @@ -400,15 +428,17 @@ def test_create_service_with_connection_string_fails_if_secondary_without_primar for service_type in SERVICES.items(): self._setup(storage_account_name, storage_account_key) - conn_string = 'AccountName={};AccountKey={};{}=www.mydomain.com;'.format( - self.account_name, self.account_key.secret, _CONNECTION_ENDPOINTS_SECONDARY.get(service_type[1])) + conn_string = "AccountName={};AccountKey={};{}=www.mydomain.com;".format( + self.account_name, self.account_key.secret, _CONNECTION_ENDPOINTS_SECONDARY.get(service_type[1]) + ) # Act # Fails if primary excluded with pytest.raises(ValueError): service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) @FileSharePreparer() def test_create_service_with_connection_string_succeeds_if_secondary_with_primary(self, **kwargs): @@ -417,98 +447,98 @@ def test_create_service_with_connection_string_succeeds_if_secondary_with_primar for service_type in SERVICES.items(): self._setup(storage_account_name, storage_account_key) - conn_string = 'AccountName={};AccountKey={};{}=www.mydomain.com;{}=www-sec.mydomain.com;'.format( - self.account_name, self.account_key.secret, + conn_string = "AccountName={};AccountKey={};{}=www.mydomain.com;{}=www-sec.mydomain.com;".format( + self.account_name, + self.account_key.secret, _CONNECTION_ENDPOINTS.get(service_type[1]), - _CONNECTION_ENDPOINTS_SECONDARY.get(service_type[1])) + _CONNECTION_ENDPOINTS_SECONDARY.get(service_type[1]), + ) # Act service = service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service is not None assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_hostname == 'www.mydomain.com' - assert service.secondary_hostname == 'www-sec.mydomain.com' + assert service.primary_hostname == "www.mydomain.com" + assert service.secondary_hostname == "www-sec.mydomain.com" @FileSharePreparer() - def test_create_service_with_custom_account_endpoint_path(self, **kwargs): # pylint: disable=too-many-statements + def test_create_service_with_custom_account_endpoint_path(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) custom_account_url = "http://local-machine:11002/custom/account/path/" + self.sas_token for service_type in SERVICES.items(): - conn_string = 'DefaultEndpointsProtocol=http;AccountName={};AccountKey={};FileEndpoint={};'.format( - self.account_name, self.account_key.secret, custom_account_url) + conn_string = "DefaultEndpointsProtocol=http;AccountName={};AccountKey={};FileEndpoint={};".format( + self.account_name, self.account_key.secret, custom_account_url + ) # Act service = service_type[0].from_connection_string( - conn_string, share_name="foo", directory_path="bar", file_path="baz") + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_hostname == 'local-machine:11002/custom/account/path' + assert service.primary_hostname == "local-machine:11002/custom/account/path" service = ShareServiceClient(account_url=custom_account_url) assert service.account_name == None assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' - assert service.url.startswith('http://local-machine:11002/custom/account/path/?') + assert service.primary_hostname == "local-machine:11002/custom/account/path" + assert service.url.startswith("http://local-machine:11002/custom/account/path/?") service = ShareClient(account_url=custom_account_url, share_name="foo", snapshot="snap") assert service.account_name == None assert service.share_name == "foo" assert service.snapshot == "snap" assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' - assert service.url.startswith('http://local-machine:11002/custom/account/path/foo?sharesnapshot=snap&') + assert service.primary_hostname == "local-machine:11002/custom/account/path" + assert service.url.startswith("http://local-machine:11002/custom/account/path/foo?sharesnapshot=snap&") service = ShareDirectoryClient( - account_url=custom_account_url, - share_name='foo', - directory_path="bar/baz", snapshot="snap" + account_url=custom_account_url, share_name="foo", directory_path="bar/baz", snapshot="snap" ) assert service.account_name == None assert service.share_name == "foo" assert service.directory_path == "bar/baz" assert service.snapshot == "snap" assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' + assert service.primary_hostname == "local-machine:11002/custom/account/path" assert service.url.startswith( - 'http://local-machine:11002/custom/account/path/foo/bar%2Fbaz?sharesnapshot=snap&' + "http://local-machine:11002/custom/account/path/foo/bar%2Fbaz?sharesnapshot=snap&" ) - service = ShareDirectoryClient(account_url=custom_account_url, share_name='foo', directory_path="") + service = ShareDirectoryClient(account_url=custom_account_url, share_name="foo", directory_path="") assert service.account_name == None assert service.share_name == "foo" assert service.directory_path == "" assert service.snapshot == None assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' - assert service.url.startswith('http://local-machine:11002/custom/account/path/foo?') + assert service.primary_hostname == "local-machine:11002/custom/account/path" + assert service.url.startswith("http://local-machine:11002/custom/account/path/foo?") service = ShareFileClient( - account_url=custom_account_url, - share_name="foo", - file_path="bar/baz/file", - snapshot="snap" + account_url=custom_account_url, share_name="foo", file_path="bar/baz/file", snapshot="snap" ) assert service.account_name == None assert service.share_name == "foo" assert service.directory_path == "bar/baz" - assert service.file_path == ["bar", "baz", "file"] + assert service.file_path, ["bar", "baz" == "file"] assert service.file_name == "file" assert service.snapshot == "snap" assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' + assert service.primary_hostname == "local-machine:11002/custom/account/path" assert service.url.startswith( - 'http://local-machine:11002/custom/account/path/foo/bar/baz/file?sharesnapshot=snap&' + "http://local-machine:11002/custom/account/path/foo/bar/baz/file?sharesnapshot=snap&" ) service = ShareFileClient(account_url=custom_account_url, share_name="foo", file_path="file") @@ -519,35 +549,37 @@ def test_create_service_with_custom_account_endpoint_path(self, **kwargs): # py assert service.file_name == "file" assert service.snapshot == None assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' - assert service.url.startswith('http://local-machine:11002/custom/account/path/foo/file?') + assert service.primary_hostname == "local-machine:11002/custom/account/path" + assert service.url.startswith("http://local-machine:11002/custom/account/path/foo/file?") - @pytest.mark.skip(reason="Client Request ID is different for every request, needs further investigation: https://github.com/Azure/azure-sdk-for-python/issues/8098") # pylint: disable=line-too-long + @pytest.mark.skip( + reason="Client Request ID is different for every request, needs further investigation: https://github.com/Azure/azure-sdk-for-python/issues/8098" + ) @FileSharePreparer() def test_client_request_id_echo(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - request_id_header_name = 'x-ms-client-request-id' + request_id_header_name = "x-ms-client-request-id" service = ShareServiceClient(self.account_url(storage_account_name, "file"), credential=self.account_key.secret) # Act make the client request ID slightly different - def first_callback(response): + def callback(response): response.http_response.status_code = 200 - response.http_response.headers[request_id_header_name] += '1' + response.http_response.headers[request_id_header_name] += "1" # Assert the client request ID validation is working with pytest.raises(AzureError): - service.get_service_properties(raw_response_hook=first_callback) + service.get_service_properties(raw_response_hook=callback) # Act remove the echoed client request ID - def second_callback(response): + def callback(response): response.status_code = 200 del response.http_response.headers[request_id_header_name] # Assert the client request ID validation is not throwing when the ID is not echoed - service.get_service_properties(raw_response_hook=second_callback) + service.get_service_properties(raw_response_hook=callback) @FileSharePreparer() @recorded_by_proxy @@ -559,8 +591,8 @@ def test_user_agent_default(self, **kwargs): service = ShareServiceClient(self.account_url(storage_account_name, "file"), credential=self.account_key.secret) def callback(response): - assert 'User-Agent' in response.http_request.headers - assert "azsdk-python-storage-file-share/{}".format(VERSION) in response.http_request.headers['User-Agent'] + assert "User-Agent" in response.http_request.headers + assert "azsdk-python-storage-file-share/{}".format(VERSION) in response.http_request.headers["User-Agent"] service.get_service_properties(raw_response_hook=callback) @@ -573,23 +605,26 @@ def test_user_agent_custom(self, **kwargs): self._setup(storage_account_name, storage_account_key) custom_app = "TestApp/v1.0" service = ShareServiceClient( - self.account_url(storage_account_name, "file"), credential=self.account_key.secret, user_agent=custom_app) + self.account_url(storage_account_name, "file"), credential=self.account_key.secret, user_agent=custom_app + ) def callback1(response): - assert 'User-Agent' in response.http_request.headers - assert ("TestApp/v1.0 azsdk-python-storage-file-share/{} Python/{} ({})".format( - VERSION, - platform.python_version(), - platform.platform())) in response.http_request.headers['User-Agent'] + assert "User-Agent" in response.http_request.headers + assert ( + "TestApp/v1.0 azsdk-python-storage-file-share/{} Python/{} ({})".format( + VERSION, platform.python_version(), platform.platform() + ) + ) in response.http_request.headers["User-Agent"] service.get_service_properties(raw_response_hook=callback1) def callback2(response): - assert 'User-Agent' in response.http_request.headers - assert ("TestApp/v2.0 TestApp/v1.0 azsdk-python-storage-file-share/{} Python/{} ({})".format( - VERSION, - platform.python_version(), - platform.platform())) in response.http_request.headers['User-Agent'] + assert "User-Agent" in response.http_request.headers + assert ( + "TestApp/v2.0 TestApp/v1.0 azsdk-python-storage-file-share/{} Python/{} ({})".format( + VERSION, platform.python_version(), platform.platform() + ) + ) in response.http_request.headers["User-Agent"] service.get_service_properties(raw_response_hook=callback2, user_agent="TestApp/v2.0") @@ -603,13 +638,14 @@ def test_user_agent_append(self, **kwargs): service = ShareServiceClient(self.account_url(storage_account_name, "file"), credential=self.account_key.secret) def callback(response): - assert 'User-Agent' in response.http_request.headers - assert ("customer_user_agent azsdk-python-storage-file-share/{} Python/{} ({})".format( - VERSION, - platform.python_version(), - platform.platform())) in response.http_request.headers['User-Agent'] + assert "User-Agent" in response.http_request.headers + assert ( + "customer_user_agent azsdk-python-storage-file-share/{} Python/{} ({})".format( + VERSION, platform.python_version(), platform.platform() + ) + ) in response.http_request.headers["User-Agent"] - service.get_service_properties(raw_response_hook=callback, user_agent='customer_user_agent') + service.get_service_properties(raw_response_hook=callback, user_agent="customer_user_agent") @FileSharePreparer() def test_error_with_malformed_conn_str(self, **kwargs): @@ -622,16 +658,13 @@ def test_error_with_malformed_conn_str(self, **kwargs): for service_type in SERVICES.items(): # Act with pytest.raises(ValueError) as e: - service_type[0].from_connection_string( - conn_str, - share_name="test", - directory_path="foo/bar", - file_path="temp/dat" + service = service_type[0].from_connection_string( + conn_str, share_name="test", directory_path="foo/bar", file_path="temp/dat" ) - if conn_str in("", "foobar", "foo;bar;baz", ";"): + if conn_str in ("", "foobar", "foo;bar;baz", ";"): assert e.value.args[0] == "Connection string is either blank or malformed." - elif conn_str in ("foobar=baz=foo" , "foo=;bar=;", "=", "=;=="): + elif conn_str in ("foobar=baz=foo", "foo=;bar=;", "=", "=;=="): assert e.value.args[0] == "Connection string missing required connection details." @FileSharePreparer() @@ -646,14 +679,14 @@ def test_closing_pipeline_client(self, **kwargs): service = client( self.account_url(storage_account_name, "file"), credential=self.account_key.secret, - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) # Assert with service: - assert hasattr(service, 'close') + assert hasattr(service, "close") service.close() @FileSharePreparer() @@ -668,8 +701,8 @@ def test_closing_pipeline_client_simple(self, **kwargs): service = client( self.account_url(storage_account_name, "file"), credential=self.account_key.secret, - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) service.close() diff --git a/sdk/storage/azure-storage-file-share/tests/test_file_client_async.py b/sdk/storage/azure-storage-file-share/tests/test_file_client_async.py index ba315d445f0c..a095e9c3dd39 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file_client_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file_client_async.py @@ -7,27 +7,26 @@ import platform import pytest +from azure.storage.fileshare import LocationMode, VERSION +from azure.storage.fileshare.aio import ShareClient, ShareDirectoryClient, ShareFileClient, ShareServiceClient from devtools_testutils.aio import recorded_by_proxy_async from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase from devtools_testutils.storage.testcase import generate_sas_token from settings.testcase import FileSharePreparer -from azure.storage.fileshare import LocationMode, VERSION -from azure.storage.fileshare.aio import ShareClient, ShareDirectoryClient, ShareFileClient, ShareServiceClient - # ------------------------------------------------------------------------------ SERVICES = { - ShareServiceClient: 'file', - ShareClient: 'file', - ShareDirectoryClient: 'file', - ShareFileClient: 'file', + ShareServiceClient: "file", + ShareClient: "file", + ShareDirectoryClient: "file", + ShareFileClient: "file", } -_CONNECTION_ENDPOINTS = {'file': 'FileEndpoint'} +_CONNECTION_ENDPOINTS = {"file": "FileEndpoint"} -_CONNECTION_ENDPOINTS_SECONDARY = {'file': 'FileSecondaryEndpoint'} +_CONNECTION_ENDPOINTS_SECONDARY = {"file": "FileSecondaryEndpoint"} class TestStorageFileClientAsync(AsyncStorageRecordedTestCase): @@ -43,16 +42,25 @@ def _teardown(self, FILE_PATH): os.remove(FILE_PATH) except: pass + # --Helpers----------------------------------------------------------------- - def validate_standard_account_endpoints(self, service, service_type, protocol='https'): + def validate_standard_account_endpoints(self, service, service_type, protocol="https"): assert service is not None assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_endpoint.startswith( - '{}://{}.{}.core.windows.net/'.format(protocol, self.account_name, service_type)) is True - assert service.secondary_endpoint.startswith( - '{}://{}-secondary.{}.core.windows.net/'.format(protocol, self.account_name, service_type)) is True + assert ( + service.primary_endpoint.startswith( + "{}://{}.{}.core.windows.net/".format(protocol, self.account_name, service_type) + ) + is True + ) + assert ( + service.secondary_endpoint.startswith( + "{}://{}-secondary.{}.core.windows.net/".format(protocol, self.account_name, service_type) + ) + is True + ) def validate_ipv6_account_endpoints(self, service, account_name, account_key, primary_endpoint, secondary_endpoint): assert service is not None @@ -74,12 +82,16 @@ async def test_create_service_with_key(self, **kwargs): for client, url in SERVICES.items(): # Act service = client( - self.account_url(storage_account_name, "file"), credential=self.account_key.secret, - share_name='foo', directory_path='bar', file_path='baz') + self.account_url(storage_account_name, "file"), + credential=self.account_key.secret, + share_name="foo", + directory_path="bar", + file_path="baz", + ) # Assert self.validate_standard_account_endpoints(service, url) - assert service.scheme == 'https' + assert service.scheme == "https" @FileSharePreparer() async def test_create_service_with_sas(self, **kwargs): @@ -91,8 +103,12 @@ async def test_create_service_with_sas(self, **kwargs): for service_type in SERVICES: # Act service = service_type( - self.account_url(storage_account_name, "file"), credential=self.sas_token, - share_name='foo', directory_path='bar', file_path='baz') + self.account_url(storage_account_name, "file"), + credential=self.sas_token, + share_name="foo", + directory_path="bar", + file_path="baz", + ) # Assert assert service is not None @@ -110,8 +126,13 @@ async def test_create_service_with_token(self, **kwargs): # Act # token credential is available for FileService try: - service_type(self.account_url(storage_account_name, "file"), credential=self.token_credential, - share_name='foo', directory_path='bar', file_path='baz') + service_type( + self.account_url(storage_account_name, "file"), + credential=self.token_credential, + share_name="foo", + directory_path="bar", + file_path="baz", + ) except ValueError: pass @@ -121,22 +142,22 @@ async def test_create_service_china(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - url = self.account_url(storage_account_name, "file").replace('core.windows.net', 'core.chinacloudapi.cn') + url = self.account_url(storage_account_name, "file").replace("core.windows.net", "core.chinacloudapi.cn") for service_type in SERVICES.items(): # Act service = service_type[0]( - url, credential=self.account_key.secret, - share_name='foo', directory_path='bar', file_path='baz') + url, credential=self.account_key.secret, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service is not None assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_hostname == '{}.{}.core.chinacloudapi.cn'.format( - self.account_name, service_type[1]) - assert service.secondary_hostname == '{}-secondary.{}.core.chinacloudapi.cn'.format( - self.account_name, service_type[1]) + assert service.primary_hostname == "{}.{}.core.chinacloudapi.cn".format(self.account_name, service_type[1]) + assert service.secondary_hostname == "{}-secondary.{}.core.chinacloudapi.cn".format( + self.account_name, service_type[1] + ) @FileSharePreparer() async def test_create_service_protocol(self, **kwargs): @@ -144,15 +165,16 @@ async def test_create_service_protocol(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - url = self.account_url(storage_account_name, "file").replace('https', 'http') + url = self.account_url(storage_account_name, "file").replace("https", "http") for service_type in SERVICES.items(): # Act service = service_type[0]( - url, credential=self.account_key.secret, share_name='foo', directory_path='bar', file_path='baz') + url, credential=self.account_key.secret, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert - self.validate_standard_account_endpoints(service, service_type[1], protocol='http') - assert service.scheme == 'http' + self.validate_standard_account_endpoints(service, service_type[1], protocol="http") + assert service.scheme == "http" @FileSharePreparer() async def test_create_service_empty_key(self, **kwargs): @@ -166,13 +188,15 @@ async def test_create_service_empty_key(self, **kwargs): with pytest.raises(ValueError) as e: service_type( self.account_url(storage_account_name, "file"), - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) - assert (str(e.value.args[0]) == - 'You need to provide either an account shared key or SAS token when creating a storage service.') + assert ( + str(e.value.args[0]) + == "You need to provide either an account shared key or SAS token when creating a storage service." + ) @FileSharePreparer() async def test_create_service_with_socket_timeout(self, **kwargs): @@ -186,17 +210,17 @@ async def test_create_service_with_socket_timeout(self, **kwargs): default_service = service_type[0]( self.account_url(storage_account_name, "file"), credential=self.account_key.secret, - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) service = service_type[0]( self.account_url(storage_account_name, "file"), credential=self.account_key.secret, connection_timeout=22, - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) # Assert @@ -205,7 +229,8 @@ async def test_create_service_with_socket_timeout(self, **kwargs): assert default_service._client._client._pipeline._transport.connection_config.timeout in [20, (20, 2000)] @pytest.mark.parametrize( - "account_url, expected_primary, expected_secondary", [ + "account_url, expected_primary, expected_secondary", + [ ( "https://myaccount.file.core.windows.net/", "myaccount.file.core.windows.net", @@ -236,7 +261,7 @@ async def test_create_service_with_socket_timeout(self, **kwargs): "myaccount-secondary-ipv6.file.core.windows.net", "myaccount-secondary-ipv6.file.core.windows.net", ), - ] + ], ) @FileSharePreparer() def test_create_service_ipv6(self, account_url, expected_primary, expected_secondary, **kwargs): @@ -245,13 +270,13 @@ def test_create_service_ipv6(self, account_url, expected_primary, expected_secon share_name, directory_path, file_path = "foo", "bar", "baz" - for service_type in SERVICES: + for service_type in SERVICES.keys(): service = service_type( account_url, credential=storage_account_key.secret, share_name=share_name, directory_path=directory_path, - file_path=file_path + file_path=file_path, ) self.validate_ipv6_account_endpoints( service, storage_account_name, storage_account_key.secret, expected_primary, expected_secondary @@ -268,7 +293,7 @@ def test_create_service_ipv6(self, account_url, expected_primary, expected_secon credential=storage_account_key.secret, share_name=share_name, directory_path=directory_path, - file_path=file_path + file_path=file_path, ) self.validate_ipv6_account_endpoints( service, storage_account_name, storage_account_key.secret, expected_primary, expected_secondary @@ -276,7 +301,7 @@ def test_create_service_ipv6(self, account_url, expected_primary, expected_secon service = ShareFileClient.from_file_url( file_url=f"{account_url}/{share_name}/{directory_path}/{file_path}-secondary", - credential=storage_account_key.secret + credential=storage_account_key.secret, ) self.validate_ipv6_account_endpoints( service, storage_account_name, storage_account_key.secret, expected_primary, expected_secondary @@ -288,14 +313,14 @@ def test_create_service_ipv6_custom_domain(self): hostname = "github.com" account_url = f"https://{hostname}" - for service_type in SERVICES: + for service_type in SERVICES.keys(): service = service_type( account_url, credential=token_credential, share_name="foo", directory_path="bar", file_path="baz", - token_intent="backup" + token_intent="backup", ) assert service is not None assert service.scheme == "https" @@ -312,16 +337,17 @@ async def test_create_service_with_connection_string_key(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - conn_string = 'AccountName={};AccountKey={};'.format(self.account_name, self.account_key.secret) + conn_string = "AccountName={};AccountKey={};".format(self.account_name, self.account_key.secret) for service_type in SERVICES.items(): # Act service = service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert self.validate_standard_account_endpoints(service, service_type[1]) - assert service.scheme == 'https' + assert service.scheme == "https" @FileSharePreparer() async def test_create_service_with_connection_string_sas(self, **kwargs): @@ -329,12 +355,13 @@ async def test_create_service_with_connection_string_sas(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - conn_string = 'AccountName={};SharedAccessSignature={};'.format(self.account_name, self.sas_token) + conn_string = "AccountName={};SharedAccessSignature={};".format(self.account_name, self.sas_token) for service_type in SERVICES.items(): # Act service = service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service is not None @@ -349,19 +376,15 @@ async def test_create_service_with_connection_string_endpoint_protocol(self, **k self._setup(storage_account_name, storage_account_key) conn_string = ( - 'AccountName={};AccountKey={};DefaultEndpointsProtocol=http;EndpointSuffix=core.chinacloudapi.cn;'.format( - self.account_name, - self.account_key.secret + "AccountName={};AccountKey={};DefaultEndpointsProtocol=http;EndpointSuffix=core.chinacloudapi.cn;".format( + self.account_name, self.account_key.secret ) ) for service_type in SERVICES.items(): # Act service = service_type[0].from_connection_string( - conn_string, - share_name='foo', - directory_path='bar', - file_path='baz' + conn_string, share_name="foo", directory_path="bar", file_path="baz" ) # Assert @@ -369,11 +392,11 @@ async def test_create_service_with_connection_string_endpoint_protocol(self, **k assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_hostname == '{}.{}.core.chinacloudapi.cn'.format( - self.account_name, service_type[1]) - assert service.secondary_hostname == '{}-secondary.{}.core.chinacloudapi.cn'.format( - self.account_name, service_type[1]) - assert service.scheme == 'http' + assert service.primary_hostname == "{}.{}.core.chinacloudapi.cn".format(self.account_name, service_type[1]) + assert service.secondary_hostname == "{}-secondary.{}.core.chinacloudapi.cn".format( + self.account_name, service_type[1] + ) + assert service.scheme == "http" @FileSharePreparer() async def test_create_service_with_connection_string_emulated(self, **kwargs): @@ -382,15 +405,12 @@ async def test_create_service_with_connection_string_emulated(self, **kwargs): self._setup(storage_account_name, storage_account_key) for service_type in SERVICES.items(): - conn_string = 'UseDevelopmentStorage=true;' + conn_string = "UseDevelopmentStorage=true;" # Act with pytest.raises(ValueError): service_type[0].from_connection_string( - conn_string, - share_name='foo', - directory_path='bar', - file_path='baz' + conn_string, share_name="foo", directory_path="bar", file_path="baz" ) @FileSharePreparer() @@ -400,15 +420,17 @@ async def test_create_service_with_connection_string_fails_if_secondary_without_ for service_type in SERVICES.items(): self._setup(storage_account_name, storage_account_key) - conn_string = 'AccountName={};AccountKey={};{}=www.mydomain.com;'.format( - self.account_name, self.account_key.secret, _CONNECTION_ENDPOINTS_SECONDARY.get(service_type[1])) + conn_string = "AccountName={};AccountKey={};{}=www.mydomain.com;".format( + self.account_name, self.account_key.secret, _CONNECTION_ENDPOINTS_SECONDARY.get(service_type[1]) + ) # Act # Fails if primary excluded with pytest.raises(ValueError): service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) @FileSharePreparer() async def test_create_service_with_connection_string_succeeds_if_secondary_with_primary(self, **kwargs): @@ -417,98 +439,99 @@ async def test_create_service_with_connection_string_succeeds_if_secondary_with_ for service_type in SERVICES.items(): self._setup(storage_account_name, storage_account_key) - conn_string = 'AccountName={};AccountKey={};{}=www.mydomain.com;{}=www-sec.mydomain.com;'.format( - self.account_name, self.account_key.secret, + conn_string = "AccountName={};AccountKey={};{}=www.mydomain.com;{}=www-sec.mydomain.com;".format( + self.account_name, + self.account_key.secret, _CONNECTION_ENDPOINTS.get(service_type[1]), - _CONNECTION_ENDPOINTS_SECONDARY.get(service_type[1])) + _CONNECTION_ENDPOINTS_SECONDARY.get(service_type[1]), + ) # Act service = service_type[0].from_connection_string( - conn_string, share_name='foo', directory_path='bar', file_path='baz') + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service is not None assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_hostname == 'www.mydomain.com' - assert service.secondary_hostname == 'www-sec.mydomain.com' + assert service.primary_hostname == "www.mydomain.com" + assert service.secondary_hostname == "www-sec.mydomain.com" @FileSharePreparer() - async def test_create_service_with_custom_account_endpoint_path(self, **kwargs): # pylint: disable=too-many-statements + async def test_create_service_with_custom_account_endpoint_path(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) custom_account_url = "http://local-machine:11002/custom/account/path/" + self.sas_token for service_type in SERVICES.items(): - conn_string = 'DefaultEndpointsProtocol=http;AccountName={};AccountKey={};FileEndpoint={};'.format( - self.account_name, self.account_key.secret, custom_account_url) + conn_string = "DefaultEndpointsProtocol=http;AccountName={};AccountKey={};FileEndpoint={};".format( + self.account_name, self.account_key.secret, custom_account_url + ) # Act service = service_type[0].from_connection_string( - conn_string, share_name="foo", directory_path="bar", file_path="baz") + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) # Assert assert service.account_name == self.account_name assert service.credential.account_name == self.account_name assert service.credential.account_key == self.account_key.secret - assert service.primary_hostname == 'local-machine:11002/custom/account/path' + assert service.primary_hostname == "local-machine:11002/custom/account/path" service = ShareServiceClient(account_url=custom_account_url) assert service.account_name == None assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' - assert service.url.startswith('http://local-machine:11002/custom/account/path/?') + assert service.primary_hostname == "local-machine:11002/custom/account/path" + assert service.url.startswith("http://local-machine:11002/custom/account/path/?") service = ShareClient(account_url=custom_account_url, share_name="foo", snapshot="snap") assert service.account_name == None assert service.share_name == "foo" assert service.snapshot == "snap" assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' - assert service.url.startswith('http://local-machine:11002/custom/account/path/foo?sharesnapshot=snap&') + assert service.primary_hostname == "local-machine:11002/custom/account/path" + assert service.url.startswith("http://local-machine:11002/custom/account/path/foo?sharesnapshot=snap&") service = ShareDirectoryClient( - account_url=custom_account_url, - share_name='foo', - directory_path="bar/baz", - snapshot="snap" + account_url=custom_account_url, share_name="foo", directory_path="bar/baz", snapshot="snap" ) assert service.account_name == None assert service.share_name == "foo" assert service.directory_path == "bar/baz" assert service.snapshot == "snap" assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' + assert service.primary_hostname == "local-machine:11002/custom/account/path" assert service.url.startswith( - 'http://local-machine:11002/custom/account/path/foo/bar%2Fbaz?sharesnapshot=snap&') + "http://local-machine:11002/custom/account/path/foo/bar%2Fbaz?sharesnapshot=snap&" + ) - service = ShareDirectoryClient(account_url=custom_account_url, share_name='foo', directory_path="") + service = ShareDirectoryClient(account_url=custom_account_url, share_name="foo", directory_path="") assert service.account_name == None assert service.share_name == "foo" assert service.directory_path == "" assert service.snapshot == None assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' - assert service.url.startswith('http://local-machine:11002/custom/account/path/foo?') + assert service.primary_hostname == "local-machine:11002/custom/account/path" + assert service.url.startswith("http://local-machine:11002/custom/account/path/foo?") service = ShareFileClient( - account_url=custom_account_url, - share_name="foo", - file_path="bar/baz/file", - snapshot="snap" + account_url=custom_account_url, share_name="foo", file_path="bar/baz/file", snapshot="snap" ) assert service.account_name == None assert service.share_name == "foo" assert service.directory_path == "bar/baz" - assert service.file_path == ["bar", "baz", "file"] + assert service.file_path, ["bar", "baz" == "file"] assert service.file_name == "file" assert service.snapshot == "snap" assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' + assert service.primary_hostname == "local-machine:11002/custom/account/path" assert service.url.startswith( - 'http://local-machine:11002/custom/account/path/foo/bar/baz/file?sharesnapshot=snap&') + "http://local-machine:11002/custom/account/path/foo/bar/baz/file?sharesnapshot=snap&" + ) service = ShareFileClient(account_url=custom_account_url, share_name="foo", file_path="file") assert service.account_name == None @@ -518,8 +541,8 @@ async def test_create_service_with_custom_account_endpoint_path(self, **kwargs): assert service.file_name == "file" assert service.snapshot == None assert service.credential == None - assert service.primary_hostname == 'local-machine:11002/custom/account/path' - assert service.url.startswith('http://local-machine:11002/custom/account/path/foo/file?') + assert service.primary_hostname == "local-machine:11002/custom/account/path" + assert service.url.startswith("http://local-machine:11002/custom/account/path/foo/file?") @FileSharePreparer() @recorded_by_proxy_async @@ -528,14 +551,11 @@ async def test_user_agent_default(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - service = ShareServiceClient( - self.account_url(storage_account_name, "file"), - credential=self.account_key.secret - ) + service = ShareServiceClient(self.account_url(storage_account_name, "file"), credential=self.account_key.secret) def callback(response): - assert 'User-Agent' in response.http_request.headers - assert "azsdk-python-storage-file-share/{}".format(VERSION) in response.http_request.headers['User-Agent'] + assert "User-Agent" in response.http_request.headers + assert "azsdk-python-storage-file-share/{}".format(VERSION) in response.http_request.headers["User-Agent"] await service.get_service_properties(raw_response_hook=callback) @@ -548,26 +568,26 @@ async def test_user_agent_custom(self, **kwargs): self._setup(storage_account_name, storage_account_key) custom_app = "TestApp/v1.0" service = ShareServiceClient( - self.account_url(storage_account_name, "file"), - credential=self.account_key.secret, - user_agent=custom_app + self.account_url(storage_account_name, "file"), credential=self.account_key.secret, user_agent=custom_app ) def callback1(response): - assert 'User-Agent' in response.http_request.headers - assert ("TestApp/v1.0 azsdk-python-storage-file-share/{} Python/{} ({})".format( - VERSION, - platform.python_version(), - platform.platform())) in response.http_request.headers['User-Agent'] + assert "User-Agent" in response.http_request.headers + assert ( + "TestApp/v1.0 azsdk-python-storage-file-share/{} Python/{} ({})".format( + VERSION, platform.python_version(), platform.platform() + ) + ) in response.http_request.headers["User-Agent"] await service.get_service_properties(raw_response_hook=callback1) def callback2(response): - assert 'User-Agent' in response.http_request.headers - assert ("TestApp/v2.0 TestApp/v1.0 azsdk-python-storage-file-share/{} Python/{} ({})".format( - VERSION, - platform.python_version(), - platform.platform())) in response.http_request.headers['User-Agent'] + assert "User-Agent" in response.http_request.headers + assert ( + "TestApp/v2.0 TestApp/v1.0 azsdk-python-storage-file-share/{} Python/{} ({})".format( + VERSION, platform.python_version(), platform.platform() + ) + ) in response.http_request.headers["User-Agent"] await service.get_service_properties(raw_response_hook=callback2, user_agent="TestApp/v2.0") @@ -578,19 +598,17 @@ async def test_user_agent_append(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - service = ShareServiceClient( - self.account_url(storage_account_name, "file"), - credential=self.account_key.secret - ) + service = ShareServiceClient(self.account_url(storage_account_name, "file"), credential=self.account_key.secret) def callback(response): - assert 'User-Agent' in response.http_request.headers - assert ("customer_user_agent azsdk-python-storage-file-share/{} Python/{} ({})".format( - VERSION, - platform.python_version(), - platform.platform())) in response.http_request.headers['User-Agent'] + assert "User-Agent" in response.http_request.headers + assert ( + "customer_user_agent azsdk-python-storage-file-share/{} Python/{} ({})".format( + VERSION, platform.python_version(), platform.platform() + ) + ) in response.http_request.headers["User-Agent"] - await service.get_service_properties(raw_response_hook=callback, user_agent='customer_user_agent') + await service.get_service_properties(raw_response_hook=callback, user_agent="customer_user_agent") @FileSharePreparer() async def test_closing_pipeline_client(self, **kwargs): @@ -604,14 +622,14 @@ async def test_closing_pipeline_client(self, **kwargs): service = client( self.account_url(storage_account_name, "file"), credential=self.account_key.secret, - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) # Assert async with service: - assert hasattr(service, 'close') + assert hasattr(service, "close") await service.close() @FileSharePreparer() @@ -626,8 +644,8 @@ async def test_closing_pipeline_client_simple(self, **kwargs): service = client( self.account_url(storage_account_name, "file"), credential=self.account_key.secret, - share_name='foo', - directory_path='bar', - file_path='baz' + share_name="foo", + directory_path="bar", + file_path="baz", ) await service.close() diff --git a/sdk/storage/azure-storage-file-share/tests/test_file_service_properties.py b/sdk/storage/azure-storage-file-share/tests/test_file_service_properties.py index eee68273f57a..b4bf349f7288 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file_service_properties.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file_service_properties.py @@ -6,11 +6,6 @@ import os import pytest - -from devtools_testutils import recorded_by_proxy -from devtools_testutils.storage import StorageRecordedTestCase -from settings.testcase import FileSharePreparer - from azure.core.exceptions import HttpResponseError from azure.storage.fileshare import ( CorsRule, @@ -23,6 +18,9 @@ SmbMultichannel, ) +from devtools_testutils import recorded_by_proxy +from devtools_testutils.storage import StorageRecordedTestCase +from settings.testcase import FileSharePreparer # ------------------------------------------------------------------------------ @@ -39,6 +37,7 @@ def _teardown(self, FILE_PATH): os.remove(FILE_PATH) except: pass + # --Helpers----------------------------------------------------------------- def _assert_metrics_equal(self, metrics1, metrics2): if metrics1 is None or metrics2 is None: @@ -57,7 +56,8 @@ def _assert_cors_equal(self, cors1, cors2): assert len(cors1) == len(cors2) - for i, rule1 in enumerate(cors1): + for i in range(0, len(cors1)): + rule1 = cors1[i] rule2 = cors2[i] assert len(rule1.allowed_origins) == len(rule2.allowed_origins) assert len(rule1.allowed_methods) == len(rule2.allowed_methods) @@ -81,45 +81,40 @@ def test_file_service_properties(self, **kwargs): protocol_properties1 = ShareProtocolSettings( smb=ShareSmbSettings( multichannel=SmbMultichannel(enabled=False), - encryption_in_transit=SmbEncryptionInTransit(required=False) + encryption_in_transit=SmbEncryptionInTransit(required=False), ) ) protocol_properties2 = ShareProtocolSettings( smb=ShareSmbSettings( - multichannel=SmbMultichannel(enabled=True), - encryption_in_transit=SmbEncryptionInTransit(required=True) + multichannel=SmbMultichannel(enabled=True), encryption_in_transit=SmbEncryptionInTransit(required=True) ) ) resp = self.fsc.set_service_properties( - hour_metrics=Metrics(), - minute_metrics=Metrics(), - cors=[], - protocol=protocol_properties1 + hour_metrics=Metrics(), minute_metrics=Metrics(), cors=[], protocol=protocol_properties1 ) assert resp is None props = self.fsc.get_service_properties() - self._assert_metrics_equal(props['hour_metrics'], Metrics()) - self._assert_metrics_equal(props['minute_metrics'], Metrics()) - self._assert_cors_equal(props['cors'], []) - assert props['protocol'].smb.multichannel.enabled == False - assert props['protocol'].smb.encryption_in_transit.required == False - + self._assert_metrics_equal(props["hour_metrics"], Metrics()) + self._assert_metrics_equal(props["minute_metrics"], Metrics()) + self._assert_cors_equal(props["cors"], []) + assert props["protocol"].smb.multichannel.enabled == False + assert props["protocol"].smb.encryption_in_transit.required == False + + with pytest.raises(TypeError): + ShareProtocolSettings(smb=ShareSmbSettings(multichannel=SmbMultichannel())) with pytest.raises(ValueError): ShareProtocolSettings(smb=ShareSmbSettings()) with pytest.raises(ValueError): ShareProtocolSettings() resp = self.fsc.set_service_properties( - hour_metrics=Metrics(), - minute_metrics=Metrics(), - cors=[], - protocol=protocol_properties2 + hour_metrics=Metrics(), minute_metrics=Metrics(), cors=[], protocol=protocol_properties2 ) assert resp is None props = self.fsc.get_service_properties() - assert props['protocol'].smb.multichannel.enabled == True - assert props['protocol'].smb.encryption_in_transit.required == True + assert props["protocol"].smb.multichannel.enabled == True + assert props["protocol"].smb.encryption_in_transit.required == True # --Test cases per feature --------------------------------------- @FileSharePreparer() @@ -136,7 +131,7 @@ def test_set_hour_metrics(self, **kwargs): # Assert received_props = self.fsc.get_service_properties() - self._assert_metrics_equal(received_props['hour_metrics'], hour_metrics) + self._assert_metrics_equal(received_props["hour_metrics"], hour_metrics) @FileSharePreparer() @recorded_by_proxy @@ -145,15 +140,16 @@ def test_set_minute_metrics(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - minute_metrics = Metrics(enabled=True, include_apis=True, - retention_policy=RetentionPolicy(enabled=True, days=5)) + minute_metrics = Metrics( + enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5) + ) # Act self.fsc.set_service_properties(minute_metrics=minute_metrics) # Assert received_props = self.fsc.get_service_properties() - self._assert_metrics_equal(received_props['minute_metrics'], minute_metrics) + self._assert_metrics_equal(received_props["minute_metrics"], minute_metrics) @FileSharePreparer() @recorded_by_proxy @@ -162,10 +158,10 @@ def test_set_cors(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - cors_rule1 = CorsRule(['www.xyz.com'], ['GET']) + cors_rule1 = CorsRule(["www.xyz.com"], ["GET"]) - allowed_origins = ['www.xyz.com', "www.ab.com", "www.bc.com"] - allowed_methods = ['GET', 'PUT'] + allowed_origins = ["www.xyz.com", "www.ab.com", "www.bc.com"] + allowed_methods = ["GET", "PUT"] max_age_in_seconds = 500 exposed_headers = ["x-ms-meta-data*", "x-ms-meta-source*", "x-ms-meta-abc", "x-ms-meta-bcd"] allowed_headers = ["x-ms-meta-data*", "x-ms-meta-target*", "x-ms-meta-xyz", "x-ms-meta-foo"] @@ -174,7 +170,8 @@ def test_set_cors(self, **kwargs): allowed_methods, max_age_in_seconds=max_age_in_seconds, exposed_headers=exposed_headers, - allowed_headers=allowed_headers) + allowed_headers=allowed_headers, + ) cors = [cors_rule1, cors_rule2] @@ -183,7 +180,7 @@ def test_set_cors(self, **kwargs): # Assert received_props = self.fsc.get_service_properties() - self._assert_cors_equal(received_props['cors'], cors) + self._assert_cors_equal(received_props["cors"], cors) # --Test cases for errors --------------------------------------- @FileSharePreparer() @@ -194,9 +191,7 @@ def test_retention_no_days(self, **kwargs): self._setup(storage_account_name, storage_account_key) # Assert - pytest.raises(ValueError, - RetentionPolicy, - True, None) + pytest.raises(ValueError, RetentionPolicy, True, None) @FileSharePreparer() @recorded_by_proxy @@ -207,9 +202,10 @@ def test_too_many_cors_rules(self, **kwargs): self._setup(storage_account_name, storage_account_key) cors = [] for i in range(0, 6): - cors.append(CorsRule(['www.xyz.com'], ['GET'])) + cors.append(CorsRule(["www.xyz.com"], ["GET"])) # Assert pytest.raises(HttpResponseError, self.fsc.set_service_properties, None, None, cors) + # ------------------------------------------------------------------------------ diff --git a/sdk/storage/azure-storage-file-share/tests/test_file_service_properties_async.py b/sdk/storage/azure-storage-file-share/tests/test_file_service_properties_async.py index 56479ca76e49..89b9a2f4c41a 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file_service_properties_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file_service_properties_async.py @@ -41,6 +41,7 @@ def _teardown(self, FILE_PATH): os.remove(FILE_PATH) except: pass + # --Helpers----------------------------------------------------------------- def _assert_metrics_equal(self, metrics1, metrics2): if metrics1 is None or metrics2 is None: @@ -94,18 +95,15 @@ async def test_file_service_properties(self, **kwargs): # Act resp = await self.fsc.set_service_properties( - hour_metrics=Metrics(), - minute_metrics=Metrics(), - cors=[], - protocol=protocol_properties1 + hour_metrics=Metrics(), minute_metrics=Metrics(), cors=[], protocol=protocol_properties1 ) assert resp is None props = await self.fsc.get_service_properties() - self._assert_metrics_equal(props['hour_metrics'], Metrics()) - self._assert_metrics_equal(props['minute_metrics'], Metrics()) - self._assert_cors_equal(props['cors'], []) - assert props['protocol'].smb.multichannel.enabled == False - assert props['protocol'].smb.encryption_in_transit.required == False + self._assert_metrics_equal(props["hour_metrics"], Metrics()) + self._assert_metrics_equal(props["minute_metrics"], Metrics()) + self._assert_cors_equal(props["cors"], []) + assert props["protocol"].smb.multichannel.enabled == False + assert props["protocol"].smb.encryption_in_transit.required == False with pytest.raises(ValueError): ShareProtocolSettings(smb=ShareSmbSettings()) @@ -113,15 +111,12 @@ async def test_file_service_properties(self, **kwargs): ShareProtocolSettings() resp = await self.fsc.set_service_properties( - hour_metrics=Metrics(), - minute_metrics=Metrics(), - cors=[], - protocol=protocol_properties2 + hour_metrics=Metrics(), minute_metrics=Metrics(), cors=[], protocol=protocol_properties2 ) assert resp is None props = await self.fsc.get_service_properties() - assert props['protocol'].smb.multichannel.enabled == True - assert props['protocol'].smb.encryption_in_transit.required == True + assert props["protocol"].smb.multichannel.enabled == True + assert props["protocol"].smb.encryption_in_transit.required == True # --Test cases per feature --------------------------------------- @FileSharePreparer() @@ -138,7 +133,7 @@ async def test_set_hour_metrics(self, **kwargs): # Assert received_props = await self.fsc.get_service_properties() - self._assert_metrics_equal(received_props['hour_metrics'], hour_metrics) + self._assert_metrics_equal(received_props["hour_metrics"], hour_metrics) @FileSharePreparer() @recorded_by_proxy_async @@ -147,15 +142,16 @@ async def test_set_minute_metrics(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - minute_metrics = Metrics(enabled=True, include_apis=True, - retention_policy=RetentionPolicy(enabled=True, days=5)) + minute_metrics = Metrics( + enabled=True, include_apis=True, retention_policy=RetentionPolicy(enabled=True, days=5) + ) # Act await self.fsc.set_service_properties(minute_metrics=minute_metrics) # Assert received_props = await self.fsc.get_service_properties() - self._assert_metrics_equal(received_props['minute_metrics'], minute_metrics) + self._assert_metrics_equal(received_props["minute_metrics"], minute_metrics) @FileSharePreparer() @recorded_by_proxy_async @@ -164,10 +160,10 @@ async def test_set_cors(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - cors_rule1 = CorsRule(['www.xyz.com'], ['GET']) + cors_rule1 = CorsRule(["www.xyz.com"], ["GET"]) - allowed_origins = ['www.xyz.com', "www.ab.com", "www.bc.com"] - allowed_methods = ['GET', 'PUT'] + allowed_origins = ["www.xyz.com", "www.ab.com", "www.bc.com"] + allowed_methods = ["GET", "PUT"] max_age_in_seconds = 500 exposed_headers = ["x-ms-meta-data*", "x-ms-meta-source*", "x-ms-meta-abc", "x-ms-meta-bcd"] allowed_headers = ["x-ms-meta-data*", "x-ms-meta-target*", "x-ms-meta-xyz", "x-ms-meta-foo"] @@ -176,7 +172,8 @@ async def test_set_cors(self, **kwargs): allowed_methods, max_age_in_seconds=max_age_in_seconds, exposed_headers=exposed_headers, - allowed_headers=allowed_headers) + allowed_headers=allowed_headers, + ) cors = [cors_rule1, cors_rule2] @@ -185,7 +182,7 @@ async def test_set_cors(self, **kwargs): # Assert received_props = await self.fsc.get_service_properties() - self._assert_cors_equal(received_props['cors'], cors) + self._assert_cors_equal(received_props["cors"], cors) # --Test cases for errors --------------------------------------- @FileSharePreparer() @@ -197,7 +194,7 @@ async def test_too_many_cors_rules(self, **kwargs): self._setup(storage_account_name, storage_account_key) cors = [] for i in range(0, 6): - cors.append(CorsRule(['www.xyz.com'], ['GET'])) + cors.append(CorsRule(["www.xyz.com"], ["GET"])) # Assert with pytest.raises(HttpResponseError): diff --git a/sdk/storage/azure-storage-file-share/tests/test_get_file.py b/sdk/storage/azure-storage-file-share/tests/test_get_file.py index f9ab7720b2b3..4478f5bd383f 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_get_file.py +++ b/sdk/storage/azure-storage-file-share/tests/test_get_file.py @@ -1,25 +1,26 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import base64 +import os import tempfile +import uuid from io import BytesIO import pytest +from azure.core.exceptions import HttpResponseError, ResourceModifiedError +from azure.storage.fileshare import ShareFileClient, ShareServiceClient from devtools_testutils import recorded_by_proxy from devtools_testutils.storage import StorageRecordedTestCase from settings.testcase import FileSharePreparer from test_helpers import ProgressTracker -from azure.core.exceptions import HttpResponseError, ResourceModifiedError -from azure.storage.fileshare import ShareFileClient, ShareServiceClient - - # ------------------------------------------------------------------------------ -TEST_FILE_PREFIX = 'file' +TEST_FILE_PREFIX = "file" # ------------------------------------------------------------------------------ @@ -35,27 +36,29 @@ def _setup(self, storage_account_name, storage_account_key): credential = storage_account_key self.fsc = ShareServiceClient( - url, credential=credential.secret, + url, + credential=credential.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) - self.share_name = self.get_resource_name('utshare') - self.directory_name = self.get_resource_name('utdir') + self.share_name = self.get_resource_name("utshare") + self.directory_name = self.get_resource_name("utdir") if not self.is_playback(): share = self.fsc.create_share(self.share_name) share.create_directory(self.directory_name) - self.byte_file = self.get_resource_name('bytefile') + self.byte_file = self.get_resource_name("bytefile") self.byte_data = self.get_random_bytes(64 * 1024 + 5) if not self.is_playback(): - byte_file = self.directory_name + '/' + self.byte_file + byte_file = self.directory_name + "/" + self.byte_file file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=byte_file, - credential=credential.secret + credential=credential.secret, ) file_client.upload_file(self.byte_data) @@ -86,15 +89,16 @@ def test_unicode_get_file_unicode_data(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_data = 'hello world啊齄丂狛狜'.encode('utf-8') + file_data = "hello world啊齄丂狛狜".encode("utf-8") file_name = self._get_file_reference() file_client = ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret, - max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + max_single_get_size=self.MAX_SINGLE_GET_SIZE, + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(file_data) # Act @@ -110,32 +114,18 @@ def test_unicode_get_file_binary_data(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - base64_data = ( - 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0' - 'xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYm' - 'ZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm' - '5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM' - '0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gI' - 'GCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNz' - 's/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRob' - 'HB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2h' - 'pamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tb' - 'a3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECA' - 'wQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9Q' - 'UVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2' - 'en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6' - 'uvs7e7v8PHy8/T19vf4+fr7/P3+/w==' - ) + base64_data = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==" binary_data = base64.b64decode(base64_data) file_name = self._get_file_reference() file_client = ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret, - max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + max_single_get_size=self.MAX_SINGLE_GET_SIZE, + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(binary_data) # Act @@ -151,15 +141,16 @@ def test_get_file_no_content(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_data = b'' + file_data = b"" file_name = self._get_file_reference() file_client = ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret, - max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + max_single_get_size=self.MAX_SINGLE_GET_SIZE, + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(file_data) # Act @@ -181,10 +172,11 @@ def test_get_file_to_bytes(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act file_content = file_client.download_file(max_concurrency=2).readall() @@ -204,15 +196,17 @@ def test_get_file_to_bytes_with_progress(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -221,11 +215,7 @@ def callback(response): # Assert assert self.byte_data == file_content - self.assert_download_progress( - len(self.byte_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(self.byte_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy @@ -237,15 +227,17 @@ def test_get_file_to_bytes_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -254,11 +246,7 @@ def callback(response): # Assert assert self.byte_data == file_content - self.assert_download_progress( - len(self.byte_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(self.byte_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy @@ -272,16 +260,18 @@ def test_get_file_to_bytes_small(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(file_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -290,11 +280,7 @@ def callback(response): # Assert assert file_data == file_content - self.assert_download_progress( - len(file_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(file_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy @@ -307,11 +293,12 @@ def test_download_file_modified(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=38, - max_chunk_get_size=38) - data = b'hello world python storage test chunks' * 5 + max_chunk_get_size=38, + ) + data = b"hello world python storage test chunks" * 5 file_client.upload_file(data) resp = file_client.download_file() chunks = resp.chunks() @@ -335,10 +322,11 @@ def test_get_file_with_iter(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act chunk_size_list = [] @@ -367,10 +355,11 @@ def test_get_file_to_stream(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -393,15 +382,17 @@ def test_get_file_to_stream_with_progress(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -425,15 +416,17 @@ def test_get_file_to_stream_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -459,16 +452,18 @@ def test_get_file_to_stream_small(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(file_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -497,18 +492,20 @@ def test_get_file_to_stream_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -534,30 +531,34 @@ def test_get_file_to_stream_with_progress_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act with tempfile.TemporaryFile() as temp_file: - bytes_read = snapshot_client.download_file( - raw_response_hook=callback, max_concurrency=2).readinto(temp_file) + bytes_read = snapshot_client.download_file(raw_response_hook=callback, max_concurrency=2).readinto( + temp_file + ) # Assert assert isinstance(bytes_read, int) temp_file.seek(0) @@ -578,30 +579,34 @@ def test_get_file_to_stream_non_parallel_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act with tempfile.TemporaryFile() as temp_file: - bytes_read = snapshot_client.download_file( - raw_response_hook=callback, max_concurrency=1).readinto(temp_file) + bytes_read = snapshot_client.download_file(raw_response_hook=callback, max_concurrency=1).readinto( + temp_file + ) # Assert assert isinstance(bytes_read, int) temp_file.seek(0) @@ -621,8 +626,9 @@ def test_get_file_to_stream_small_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + ) file_client.upload_file(file_data) # Create a snapshot of the share and delete the file @@ -633,23 +639,26 @@ def test_get_file_to_stream_small_from_snapshot(self, **kwargs): snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act with tempfile.TemporaryFile() as temp_file: - bytes_read = snapshot_client.download_file( - raw_response_hook=callback, max_concurrency=1).readinto(temp_file) + bytes_read = snapshot_client.download_file(raw_response_hook=callback, max_concurrency=1).readinto( + temp_file + ) # Assert assert isinstance(bytes_read, int) temp_file.seek(0) @@ -669,10 +678,11 @@ def test_ranged_get_file_to_path(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act end_range = self.MAX_SINGLE_GET_SIZE + 1024 @@ -682,7 +692,7 @@ def test_ranged_get_file_to_path(self, **kwargs): assert isinstance(bytes_read, int) temp_file.seek(0) actual = temp_file.read() - assert self.byte_data[1:end_range + 1] == actual + assert self.byte_data[1 : end_range + 1] == actual @pytest.mark.live_test_only @FileSharePreparer() @@ -696,10 +706,11 @@ def test_ranged_get_file_to_path_with_single_byte(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act end_range = self.MAX_SINGLE_GET_SIZE + 1024 @@ -719,15 +730,16 @@ def test_ranged_get_file_to_bytes_with_zero_byte(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_data = b'' + file_data = b"" file_name = self._get_file_reference() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(file_data) # Act @@ -750,15 +762,17 @@ def test_ranged_get_file_to_path_with_progress(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -768,20 +782,16 @@ def callback(response): with tempfile.TemporaryFile() as temp_file: length = end_range - start_range + 1 bytes_read = file_client.download_file( - offset=start_range, - length=length, - raw_response_hook=callback, - max_concurrency=2).readinto(temp_file) + offset=start_range, length=length, raw_response_hook=callback, max_concurrency=2 + ).readinto(temp_file) # Assert assert isinstance(bytes_read, int) temp_file.seek(0) actual = temp_file.read() - assert self.byte_data[start_range:end_range + 1] == actual + assert self.byte_data[start_range : end_range + 1] == actual self.assert_download_progress( - end_range - start_range + 1, - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + end_range - start_range + 1, self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress + ) @FileSharePreparer() @recorded_by_proxy @@ -793,10 +803,11 @@ def test_ranged_get_file_to_path_small(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -817,10 +828,11 @@ def test_ranged_get_file_to_path_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -846,10 +858,11 @@ def test_ranged_get_file_to_path_invalid_range_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(file_data) # Act @@ -870,7 +883,6 @@ def test_ranged_get_file_to_path_invalid_range_non_parallel(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - self._setup(storage_account_name, storage_account_key) file_size = 1024 file_data = self.get_random_bytes(file_size) @@ -878,10 +890,11 @@ def test_ranged_get_file_to_path_invalid_range_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(file_data) # Act @@ -905,19 +918,20 @@ def test_get_file_to_text(self, **kwargs): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) - text_file = self.get_resource_name('textfile') + text_file = self.get_resource_name("textfile") text_data = self.get_random_text_data(self.MAX_SINGLE_GET_SIZE + 1) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + text_file, + file_path=self.directory_name + "/" + text_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(text_data) # Act - file_content = file_client.download_file(max_concurrency=2, encoding='utf-8').readall() + file_content = file_client.download_file(max_concurrency=2, encoding="utf-8").readall() # Assert assert text_data == file_content @@ -931,35 +945,36 @@ def test_get_file_to_text_with_progress(self, **kwargs): # parallel tests introduce random order of requests, can only run live self._setup(storage_account_name, storage_account_key) - text_file = self.get_resource_name('textfile') + text_file = self.get_resource_name("textfile") text_data = self.get_random_text_data(self.MAX_SINGLE_GET_SIZE + 1) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + text_file, + file_path=self.directory_name + "/" + text_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(text_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act file_content = file_client.download_file( - raw_response_hook=callback, max_concurrency=2, encoding='utf-8').readall() + raw_response_hook=callback, max_concurrency=2, encoding="utf-8" + ).readall() # Assert assert text_data == file_content self.assert_download_progress( - len(text_data.encode('utf-8')), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + len(text_data.encode("utf-8")), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress + ) @FileSharePreparer() @recorded_by_proxy @@ -973,30 +988,29 @@ def test_get_file_to_text_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + text_file, + file_path=self.directory_name + "/" + text_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(text_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act file_content = file_client.download_file( - raw_response_hook=callback, max_concurrency=1, encoding='utf-8').readall() + raw_response_hook=callback, max_concurrency=1, encoding="utf-8" + ).readall() # Assert assert text_data == file_content - self.assert_download_progress( - len(text_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(text_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy @@ -1010,29 +1024,27 @@ def test_get_file_to_text_small(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(file_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act - file_content = file_client.download_file(raw_response_hook=callback, encoding='utf-8').readall() + file_content = file_client.download_file(raw_response_hook=callback, encoding="utf-8").readall() # Assert assert file_data == file_content - self.assert_download_progress( - len(file_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(file_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy @@ -1041,20 +1053,21 @@ def test_get_file_to_text_with_encoding(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - text = 'hello 啊齄丂狛狜 world' - data = text.encode('utf-16') + text = "hello 啊齄丂狛狜 world" + data = text.encode("utf-16") file_name = self._get_file_reference() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(data) # Act - file_content = file_client.download_file(encoding='UTF-16').readall() + file_content = file_client.download_file(encoding="UTF-16").readall() # Assert assert text == file_content @@ -1066,35 +1079,33 @@ def test_get_file_to_text_with_encoding_and_progress(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - text = 'hello 啊齄丂狛狜 world' - data = text.encode('utf-16') + text = "hello 啊齄丂狛狜 world" + data = text.encode("utf-16") file_name = self._get_file_reference() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(data) # Act progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) - file_content = file_client.download_file(raw_response_hook=callback, encoding='UTF-16').readall() + file_content = file_client.download_file(raw_response_hook=callback, encoding="UTF-16").readall() # Assert assert text == file_content - self.assert_download_progress( - len(data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy @@ -1106,10 +1117,11 @@ def test_get_file_non_seekable(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -1133,10 +1145,11 @@ def test_get_file_non_seekable_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -1158,18 +1171,20 @@ def test_get_file_non_seekable_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -1196,18 +1211,20 @@ def test_get_file_non_seekable_parallel_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -1228,16 +1245,18 @@ def test_get_file_exact_get_size(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(byte_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -1246,11 +1265,7 @@ def callback(response): # Assert assert byte_data == file_content.readall() - self.assert_download_progress( - len(byte_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(byte_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @pytest.mark.live_test_only @FileSharePreparer() @@ -1266,16 +1281,18 @@ def test_get_file_exact_chunk_size(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_client.upload_file(byte_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -1284,11 +1301,7 @@ def callback(response): # Assert assert byte_data == file_content.readall() - self.assert_download_progress( - len(byte_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(byte_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @pytest.mark.live_test_only @FileSharePreparer() @@ -1302,10 +1315,11 @@ def test_get_file_with_md5(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act file_content = file_client.download_file(validate_content=True) @@ -1325,10 +1339,11 @@ def test_get_file_range_with_md5(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_content = file_client.download_file(offset=0, length=1024, validate_content=True) @@ -1336,14 +1351,14 @@ def test_get_file_range_with_md5(self, **kwargs): assert file_content.properties.content_settings.content_md5 is None props = file_client.get_file_properties() - props.content_settings.content_md5 = b'MDAwMDAwMDA=' + props.content_settings.content_md5 = b"MDAwMDAwMDA=" file_client.set_http_headers(props.content_settings) # Act file_content = file_client.download_file(offset=0, length=1024, validate_content=True) # Assert - assert b'MDAwMDAwMDA=' == file_content.properties.content_settings.content_md5 + assert b"MDAwMDAwMDA=" == file_content.properties.content_settings.content_md5 @FileSharePreparer() @recorded_by_proxy @@ -1351,15 +1366,15 @@ def test_get_file_server_encryption(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - self._setup(storage_account_name, storage_account_key) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act file_content = file_client.download_file(offset=0, length=1024, validate_content=True) @@ -1373,15 +1388,15 @@ def test_get_file_properties_server_encryption(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - self._setup(storage_account_name, storage_account_key) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act props = file_client.get_file_properties() @@ -1401,10 +1416,11 @@ def test_get_file_progress_single_get(self, **kwargs): file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + ) - data = b'a' * 512 + data = b"a" * 512 file.upload_file(data) progress = ProgressTracker(len(data), len(data)) @@ -1427,12 +1443,13 @@ def test_get_file_progress_chunked(self, **kwargs): file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=1024, - max_chunk_get_size=1024) + max_chunk_get_size=1024, + ) - data = b'a' * 5120 + data = b"a" * 5120 file.upload_file(data) progress = ProgressTracker(len(data), 1024) @@ -1456,12 +1473,13 @@ def test_get_file_progress_chunked_parallel(self, **kwargs): file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=1024, - max_chunk_get_size=1024) + max_chunk_get_size=1024, + ) - data = b'a' * 5120 + data = b"a" * 5120 file.upload_file(data) progress = ProgressTracker(len(data), 1024) @@ -1485,12 +1503,13 @@ def test_get_file_progress_range_readinto(self, **kwargs): file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=1024, - max_chunk_get_size=1024) + max_chunk_get_size=1024, + ) - data = b'a' * 5120 + data = b"a" * 5120 file.upload_file(data) length = 4096 @@ -1499,10 +1518,7 @@ def test_get_file_progress_range_readinto(self, **kwargs): # Act stream = file.download_file( - offset=512, - length=length, - max_concurrency=3, - progress_hook=progress.assert_progress + offset=512, length=length, max_concurrency=3, progress_hook=progress.assert_progress ) read = stream.readinto(result) @@ -1510,4 +1526,5 @@ def test_get_file_progress_range_readinto(self, **kwargs): progress.assert_complete() assert length == read + # ------------------------------------------------------------------------------ diff --git a/sdk/storage/azure-storage-file-share/tests/test_get_file_async.py b/sdk/storage/azure-storage-file-share/tests/test_get_file_async.py index c15f490834e4..0d97b85fb20c 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_get_file_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_get_file_async.py @@ -1,26 +1,27 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import base64 +import os import tempfile +import uuid from io import BytesIO import pytest +from azure.core.exceptions import HttpResponseError, ResourceModifiedError +from azure.storage.fileshare import FileProperties +from azure.storage.fileshare.aio import ShareFileClient, ShareServiceClient from devtools_testutils.aio import recorded_by_proxy_async from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase from settings.testcase import FileSharePreparer from test_helpers_async import ProgressTracker -from azure.core.exceptions import HttpResponseError, ResourceModifiedError -from azure.storage.fileshare import FileProperties -from azure.storage.fileshare.aio import ShareFileClient, ShareServiceClient - - # ------------------------------------------------------------------------------ -TEST_FILE_PREFIX = 'file' +TEST_FILE_PREFIX = "file" # ------------------------------------------------------------------------------ @@ -38,14 +39,15 @@ async def _setup(self, storage_account_name, storage_account_key): credential = storage_account_key self.fsc = ShareServiceClient( - url, credential=credential.secret, + url, + credential=credential.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, ) - self.share_name = self.get_resource_name('utshare') - self.directory_name = self.get_resource_name('utdir') - self.byte_file = self.get_resource_name('bytefile') + self.share_name = self.get_resource_name("utshare") + self.directory_name = self.get_resource_name("utdir") + self.byte_file = self.get_resource_name("bytefile") self.byte_data = self.get_random_bytes(64 * 1024 + 5) if not self.is_playback(): try: @@ -53,12 +55,12 @@ async def _setup(self, storage_account_name, storage_account_key): await share.create_directory(self.directory_name) except: pass - byte_file = self.directory_name + '/' + self.byte_file + byte_file = self.directory_name + "/" + self.byte_file file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, file_path=byte_file, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) try: await file_client.upload_file(self.byte_data) @@ -88,15 +90,16 @@ async def test_unicode_get_file_unicode_data(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - file_data = 'hello world啊齄丂狛狜'.encode('utf-8') + file_data = "hello world啊齄丂狛狜".encode("utf-8") file_name = self._get_file_reference() file_client = ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret, - max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + max_single_get_size=self.MAX_SINGLE_GET_SIZE, + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(file_data) # Act @@ -114,32 +117,18 @@ async def test_unicode_get_file_binary_data(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - base64_data = ( - 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0' - 'xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYm' - 'ZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm' - '5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM' - '0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gI' - 'GCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNz' - 's/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRob' - 'HB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2h' - 'pamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tb' - 'a3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECA' - 'wQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9Q' - 'UVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2' - 'en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6' - 'uvs7e7v8PHy8/T19vf4+fr7/P3+/w==' - ) + base64_data = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/wABAgMEBQYHCAkKCwwNDg8QERITFBUWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+f4CBgoOEhYaHiImKi4yNjo+QkZKTlJWWl5iZmpucnZ6foKGio6SlpqeoqaqrrK2ur7CxsrO0tba3uLm6u7y9vr/AwcLDxMXGx8jJysvMzc7P0NHS09TV1tfY2drb3N3e3+Dh4uPk5ebn6Onq6+zt7u/w8fLz9PX29/j5+vv8/f7/AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==" binary_data = base64.b64decode(base64_data) file_name = self._get_file_reference() file_client = ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret, - max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + max_single_get_size=self.MAX_SINGLE_GET_SIZE, + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(binary_data) # Act @@ -157,15 +146,15 @@ async def test_get_file_no_content(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - file_data = b'' + file_data = b"" file_name = self._get_file_reference() file_client = ShareFileClient( - self.account_url(storage_account_name, "file"), - share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret, - max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE + self.account_url(storage_account_name, "file"), + share_name=self.share_name, + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + max_single_get_size=self.MAX_SINGLE_GET_SIZE, + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, ) await file_client.upload_file(file_data) @@ -190,10 +179,11 @@ async def test_get_file_to_bytes(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act file_output = await file_client.download_file(max_concurrency=2) @@ -215,15 +205,17 @@ async def test_get_file_to_bytes_with_progress(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -233,11 +225,7 @@ def callback(response): # Assert assert self.byte_data == file_content - self.assert_download_progress( - len(self.byte_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(self.byte_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy_async @@ -250,15 +238,17 @@ async def test_get_file_to_bytes_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -268,11 +258,7 @@ def callback(response): # Assert assert self.byte_data == file_content - self.assert_download_progress( - len(self.byte_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(self.byte_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy_async @@ -287,16 +273,18 @@ async def test_get_file_to_bytes_small(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(file_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -306,11 +294,7 @@ def callback(response): # Assert assert file_data == file_content - self.assert_download_progress( - len(file_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(file_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy_async @@ -323,11 +307,12 @@ async def test_download_file_modified(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=38, - max_chunk_get_size=38) - data = b'hello world python storage test chunks' * 5 + max_chunk_get_size=38, + ) + data = b"hello world python storage test chunks" * 5 await file_client.upload_file(data) resp = await file_client.download_file() chunks = resp.chunks() @@ -352,10 +337,11 @@ async def test_get_file_to_stream(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -382,10 +368,11 @@ async def test_get_file_with_iter(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act chunk_size_list = [] @@ -415,15 +402,17 @@ async def test_get_file_to_stream_with_progress(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -450,15 +439,17 @@ async def test_get_file_to_stream_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -487,16 +478,18 @@ async def test_get_file_to_stream_small(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(file_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -528,18 +521,20 @@ async def test_get_file_to_stream_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) await file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -568,23 +563,26 @@ async def test_get_file_to_stream_with_progress_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) await file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -614,23 +612,26 @@ async def test_get_file_to_stream_non_parallel_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) await file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -659,8 +660,9 @@ async def test_get_file_to_stream_small_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + ) await file_client.upload_file(file_data) # Create a snapshot of the share and delete the file @@ -671,16 +673,18 @@ async def test_get_file_to_stream_small_from_snapshot(self, **kwargs): snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -709,23 +713,24 @@ async def test_ranged_get_file_to_path(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act start = 4 end_range = self.MAX_SINGLE_GET_SIZE + 1024 with tempfile.TemporaryFile() as temp_file: - props = await file_client.download_file(offset=start, length=end_range-start+1, max_concurrency=2) + props = await file_client.download_file(offset=start, length=end_range - start + 1, max_concurrency=2) read_bytes = await props.readinto(temp_file) # Assert assert isinstance(read_bytes, int) temp_file.seek(0) actual = temp_file.read() - assert self.byte_data[start:end_range + 1] == actual + assert self.byte_data[start : end_range + 1] == actual @pytest.mark.live_test_only @FileSharePreparer() @@ -740,10 +745,11 @@ async def test_ranged_get_file_to_path_with_single_byte(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act end_range = self.MAX_SINGLE_GET_SIZE + 1024 @@ -766,15 +772,15 @@ async def test_ranged_get_file_to_bytes_with_zero_byte(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - file_data = b'' + file_data = b"" file_name = self._get_file_reference() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, ) await file_client.upload_file(file_data) @@ -801,15 +807,17 @@ async def test_ranged_get_file_to_path_with_progress(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -818,22 +826,17 @@ def callback(response): end_range = self.MAX_SINGLE_GET_SIZE + 1024 with tempfile.TemporaryFile() as temp_file: props = await file_client.download_file( - offset=start_range, - length=end_range - start_range + 1, - max_concurrency=2, - raw_response_hook=callback) + offset=start_range, length=end_range - start_range + 1, max_concurrency=2, raw_response_hook=callback + ) read_bytes = await props.readinto(temp_file) # Assert assert isinstance(read_bytes, int) temp_file.seek(0) actual = temp_file.read() - assert self.byte_data[start_range:end_range + 1] == actual + assert self.byte_data[start_range : end_range + 1] == actual self.assert_download_progress( - end_range - start_range + 1, - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress + end_range - start_range + 1, self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress ) @FileSharePreparer() @@ -847,10 +850,11 @@ async def test_ranged_get_file_to_path_small(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -874,10 +878,11 @@ async def test_ranged_get_file_to_path_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -906,10 +911,11 @@ async def test_ranged_get_file_to_path_invalid_range_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(file_data) # Act @@ -930,7 +936,6 @@ async def test_ranged_get_file_to_path_invalid_range_non_parallel(self, **kwargs storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - # Arrange await self._setup(storage_account_name, storage_account_key) file_size = 1024 @@ -939,17 +944,18 @@ async def test_ranged_get_file_to_path_invalid_range_non_parallel(self, **kwargs file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(file_data) # Act start = 4 end_range = 2 * self.MAX_SINGLE_GET_SIZE with tempfile.TemporaryFile() as temp_file: - props = await file_client.download_file(offset=start, length=end_range-start+1, max_concurrency=1) + props = await file_client.download_file(offset=start, length=end_range - start + 1, max_concurrency=1) read_bytes = await props.readinto(temp_file) # Assert @@ -968,19 +974,20 @@ async def test_get_file_to_text(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - text_file = self.get_resource_name('textfile') + text_file = self.get_resource_name("textfile") text_data = self.get_random_text_data(self.MAX_SINGLE_GET_SIZE + 1) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + text_file, + file_path=self.directory_name + "/" + text_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(text_data) # Act - file_content = await file_client.download_file(max_concurrency=2, encoding='utf-8') + file_content = await file_client.download_file(max_concurrency=2, encoding="utf-8") file_content = await file_content.readall() # Assert @@ -996,36 +1003,35 @@ async def test_get_file_to_text_with_progress(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - text_file = self.get_resource_name('textfile') + text_file = self.get_resource_name("textfile") text_data = self.get_random_text_data(self.MAX_SINGLE_GET_SIZE + 1) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + text_file, + file_path=self.directory_name + "/" + text_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(text_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act - file_content = await file_client.download_file( - raw_response_hook=callback, max_concurrency=2, encoding='utf-8') + file_content = await file_client.download_file(raw_response_hook=callback, max_concurrency=2, encoding="utf-8") file_content = await file_content.readall() # Assert assert text_data == file_content self.assert_download_progress( - len(text_data.encode('utf-8')), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + len(text_data.encode("utf-8")), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress + ) @FileSharePreparer() @recorded_by_proxy_async @@ -1040,31 +1046,28 @@ async def test_get_file_to_text_non_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + text_file, + file_path=self.directory_name + "/" + text_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(text_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act - file_content = await file_client.download_file( - raw_response_hook=callback, max_concurrency=1, encoding='utf-8') + file_content = await file_client.download_file(raw_response_hook=callback, max_concurrency=1, encoding="utf-8") file_content = await file_content.readall() # Assert assert text_data == file_content - self.assert_download_progress( - len(text_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(text_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy_async @@ -1079,30 +1082,28 @@ async def test_get_file_to_text_small(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(file_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) # Act - file_content = await file_client.download_file(raw_response_hook=callback, encoding='utf-8') + file_content = await file_client.download_file(raw_response_hook=callback, encoding="utf-8") file_content = await file_content.readall() # Assert assert file_data == file_content - self.assert_download_progress( - len(file_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(file_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy_async @@ -1112,20 +1113,21 @@ async def test_get_file_to_text_with_encoding(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - text = 'hello 啊齄丂狛狜 world' - data = text.encode('utf-16') + text = "hello 啊齄丂狛狜 world" + data = text.encode("utf-16") file_name = self._get_file_reference() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(data) # Act - file_content = await file_client.download_file(encoding='UTF-16') + file_content = await file_client.download_file(encoding="UTF-16") file_content = await file_content.readall() # Assert @@ -1139,36 +1141,34 @@ async def test_get_file_to_text_with_encoding_and_progress(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - text = 'hello 啊齄丂狛狜 world' - data = text.encode('utf-16') + text = "hello 啊齄丂狛狜 world" + data = text.encode("utf-16") file_name = self._get_file_reference() file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(data) # Act progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) - file_content = await file_client.download_file(raw_response_hook=callback, encoding='UTF-16') + file_content = await file_client.download_file(raw_response_hook=callback, encoding="UTF-16") file_content = await file_content.readall() # Assert assert text == file_content - self.assert_download_progress( - len(data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @FileSharePreparer() @recorded_by_proxy_async @@ -1181,10 +1181,11 @@ async def test_get_file_non_seekable(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -1211,10 +1212,11 @@ async def test_get_file_non_seekable_parallel(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -1239,18 +1241,20 @@ async def test_get_file_non_seekable_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) await file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -1280,18 +1284,20 @@ async def test_get_file_non_seekable_parallel_from_snapshot(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + self.byte_file, + credential=storage_account_key.secret, + ) await file_client.delete_file() snapshot_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, snapshot=share_snapshot, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act with tempfile.TemporaryFile() as temp_file: @@ -1315,16 +1321,18 @@ async def test_get_file_exact_get_size(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(byte_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -1334,11 +1342,7 @@ def callback(response): # Assert assert byte_data == file_bytes - self.assert_download_progress( - len(byte_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(byte_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @pytest.mark.live_test_only @FileSharePreparer() @@ -1355,16 +1359,18 @@ async def test_get_file_exact_chunk_size(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) await file_client.upload_file(byte_data) progress = [] + def callback(response): - current = response.context['download_stream_current'] - total = response.context['data_stream_total'] + current = response.context["download_stream_current"] + total = response.context["data_stream_total"] if current is not None: progress.append((current, total)) @@ -1374,11 +1380,7 @@ def callback(response): # Assert assert byte_data == file_bytes - self.assert_download_progress( - len(byte_data), - self.MAX_CHUNK_GET_SIZE, - self.MAX_SINGLE_GET_SIZE, - progress) + self.assert_download_progress(len(byte_data), self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) @pytest.mark.live_test_only @FileSharePreparer() @@ -1393,10 +1395,11 @@ async def test_get_file_with_md5(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act file_content = await file_client.download_file(validate_content=True) @@ -1417,10 +1420,11 @@ async def test_get_file_range_with_md5(self, **kwargs): file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) file_content = await file_client.download_file(offset=0, length=1024, validate_content=True) @@ -1429,14 +1433,14 @@ async def test_get_file_range_with_md5(self, **kwargs): # Arrange props = await file_client.get_file_properties() - props.content_settings.content_md5 = b'MDAwMDAwMDA=' + props.content_settings.content_md5 = b"MDAwMDAwMDA=" await file_client.set_http_headers(props.content_settings) # Act file_content = await file_client.download_file(offset=0, length=1024, validate_content=True) # Assert - assert b'MDAwMDAwMDA=' == file_content.properties.content_settings.content_md5 + assert b"MDAwMDAwMDA=" == file_content.properties.content_settings.content_md5 @FileSharePreparer() @recorded_by_proxy_async @@ -1444,16 +1448,16 @@ async def test_get_file_server_encryption(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - - #Arrange + # Arrange await self._setup(storage_account_name, storage_account_key) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act file_content = await file_client.download_file(offset=0, length=1024, validate_content=True) @@ -1467,16 +1471,16 @@ async def test_get_file_properties_server_encryption(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - # Arrange await self._setup(storage_account_name, storage_account_key) file_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + self.byte_file, + file_path=self.directory_name + "/" + self.byte_file, credential=storage_account_key.secret, max_single_get_size=self.MAX_SINGLE_GET_SIZE, - max_chunk_get_size=self.MAX_CHUNK_GET_SIZE) + max_chunk_get_size=self.MAX_CHUNK_GET_SIZE, + ) # Act props = await file_client.get_file_properties() @@ -1497,10 +1501,11 @@ async def test_get_file_progress_single_get(self, **kwargs): file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, - credential=storage_account_key.secret) + file_path=self.directory_name + "/" + file_name, + credential=storage_account_key.secret, + ) - data = b'a' * 512 + data = b"a" * 512 await file.upload_file(data) progress = ProgressTracker(len(data), len(data)) @@ -1524,12 +1529,13 @@ async def test_get_file_progress_chunked(self, **kwargs): file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=1024, - max_chunk_get_size=1024) + max_chunk_get_size=1024, + ) - data = b'a' * 5120 + data = b"a" * 5120 await file.upload_file(data) progress = ProgressTracker(len(data), 1024) @@ -1554,12 +1560,13 @@ async def test_get_file_progress_chunked_parallel(self, **kwargs): file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=1024, - max_chunk_get_size=1024) + max_chunk_get_size=1024, + ) - data = b'a' * 5120 + data = b"a" * 5120 await file.upload_file(data) progress = ProgressTracker(len(data), 1024) @@ -1584,12 +1591,13 @@ async def test_get_file_progress_range_readinto(self, **kwargs): file = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=self.share_name, - file_path=self.directory_name + '/' + file_name, + file_path=self.directory_name + "/" + file_name, credential=storage_account_key.secret, max_single_get_size=1024, - max_chunk_get_size=1024) + max_chunk_get_size=1024, + ) - data = b'a' * 5120 + data = b"a" * 5120 await file.upload_file(data) length = 4096 @@ -1598,10 +1606,7 @@ async def test_get_file_progress_range_readinto(self, **kwargs): # Act stream = await file.download_file( - offset=512, - length=length, - max_concurrency=3, - progress_hook=progress.assert_progress + offset=512, length=length, max_concurrency=3, progress_hook=progress.assert_progress ) read = await stream.readinto(result) diff --git a/sdk/storage/azure-storage-file-share/tests/test_handle.py b/sdk/storage/azure-storage-file-share/tests/test_handle.py index 39b80c88c07c..a2feef539ef9 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_handle.py +++ b/sdk/storage/azure-storage-file-share/tests/test_handle.py @@ -16,7 +16,7 @@ # ------------------------------------------------------------------------------ -TEST_SHARE_NAME = 'test-share' +TEST_SHARE_NAME = "test-share" # ------------------------------------------------------------------------------ @@ -110,10 +110,9 @@ def test_list_handles_with_marker(self, **kwargs): old_handle = handles[0] # Continue listing - remaining_handles = list(next( - root.list_handles(recursive=True).by_page( - continuation_token=handle_generator.continuation_token) - )) + remaining_handles = list( + next(root.list_handles(recursive=True).by_page(continuation_token=handle_generator.continuation_token)) + ) self._validate_handles(handles) # Make sure the old handle did not appear @@ -133,7 +132,7 @@ def test_list_handles_on_directory(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = self.fsc.get_share_client(TEST_SHARE_NAME) - dir = share.get_directory_client('testdir') + dir = share.get_directory_client("testdir") # Act handles = list(dir.list_handles(recursive=True)) @@ -159,7 +158,7 @@ def test_list_handles_on_file(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = self.fsc.get_share_client(TEST_SHARE_NAME) - client = share.get_file_client('testdir/test.txt') + client = share.get_file_client("testdir/test.txt") # Act handles = list(client.list_handles()) @@ -185,13 +184,13 @@ def test_close_single_handle(self, **kwargs): # Act with pytest.raises(ValueError): - root.close_handle('*') + root.close_handle("*") handles_info = root.close_handle(handles[0]) # Assert 1 handle has been closed - assert 1 == handles_info['closed_handles_count'] - assert handles_info['failed_handles_count'] == 0 + assert 1 == handles_info["closed_handles_count"] + assert handles_info["failed_handles_count"] == 0 @pytest.mark.playback_test_only @FileSharePreparer() @@ -213,8 +212,8 @@ def test_close_all_handle(self, **kwargs): handles_info = root.close_all_handles(recursive=True) # Assert at least 1 handle has been closed - assert handles_info['closed_handles_count'] > 1 - assert handles_info['failed_handles_count'] == 0 + assert handles_info["closed_handles_count"] > 1 + assert handles_info["failed_handles_count"] == 0 @pytest.mark.playback_test_only @FileSharePreparer() @@ -227,19 +226,19 @@ def test_list_handles_access_rights(self, **kwargs): # only run when recording, or playing back in CI self._setup(storage_account_name, storage_account_key) - share = self.fsc.get_share_client('mytestshare') - root = share.get_directory_client('testdir') - file_client = root.get_file_client('testfile.txt') + share = self.fsc.get_share_client("mytestshare") + root = share.get_directory_client("testdir") + file_client = root.get_file_client("testfile.txt") # Act handles = list(file_client.list_handles()) # Assert self._validate_handles(handles) - assert handles[0]['access_rights'][0] == 'Write' - assert handles[0]['client_name'] is not None + assert handles[0]["access_rights"][0] == "Write" + assert handles[0]["client_name"] is not None # ------------------------------------------------------------------------------ -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/sdk/storage/azure-storage-file-share/tests/test_handle_async.py b/sdk/storage/azure-storage-file-share/tests/test_handle_async.py index 8b540ea2074f..048f1edfe110 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_handle_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_handle_async.py @@ -15,7 +15,7 @@ # ------------------------------------------------------------------------------ -TEST_SHARE_NAME = 'test-share' +TEST_SHARE_NAME = "test-share" # ------------------------------------------------------------------------------ @@ -63,13 +63,13 @@ async def test_close_single_handle(self, **kwargs): # Act with pytest.raises(ValueError): - await root.close_handle('*') + await root.close_handle("*") handles_info = await root.close_handle(handles[0]) # Assert 1 handle has been closed - assert 1 == handles_info['closed_handles_count'] - assert handles_info['failed_handles_count'] == 0 + assert 1 == handles_info["closed_handles_count"] + assert handles_info["failed_handles_count"] == 0 @pytest.mark.playback_test_only @FileSharePreparer() @@ -93,8 +93,8 @@ async def test_close_all_handle(self, **kwargs): handles_info = await root.close_all_handles(recursive=True) # Assert at least 1 handle has been closed - assert handles_info['closed_handles_count'] > 1 - assert handles_info['failed_handles_count'] == 0 + assert handles_info["closed_handles_count"] > 1 + assert handles_info["failed_handles_count"] == 0 @pytest.mark.playback_test_only @FileSharePreparer() @@ -107,9 +107,9 @@ async def test_list_handles_access_rights(self, **kwargs): # only run when recording, or playing back in CI self._setup(storage_account_name, storage_account_key) - share = self.fsc.get_share_client('mytestshare') - root = share.get_directory_client('testdir') - file_client = root.get_file_client('testfile.txt') + share = self.fsc.get_share_client("mytestshare") + root = share.get_directory_client("testdir") + file_client = root.get_file_client("testfile.txt") # Act handles = [] @@ -118,10 +118,10 @@ async def test_list_handles_access_rights(self, **kwargs): # Assert self._validate_handles(handles) - assert handles[0]['access_rights'][0] == 'Write' - assert handles[0]['client_name'] is not None + assert handles[0]["access_rights"][0] == "Write" + assert handles[0]["client_name"] is not None # ------------------------------------------------------------------------------ -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/sdk/storage/azure-storage-file-share/tests/test_helpers.py b/sdk/storage/azure-storage-file-share/tests/test_helpers.py index 1514a04858af..cd4e59c81d99 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_helpers.py +++ b/sdk/storage/azure-storage-file-share/tests/test_helpers.py @@ -4,14 +4,12 @@ # license information. # -------------------------------------------------------------------------- -from typing import Any, Dict, Optional - -from requests import Response +from typing import Any, Dict, Iterator, Optional from typing_extensions import Self -from urllib3 import HTTPResponse -from azure.core.pipeline.transport import HttpTransport, RequestsTransportResponse # pylint: disable=no-name-in-module +from azure.core.pipeline.transport import HttpTransport from azure.core.rest import HttpRequest +from azure.core.rest._http_response_impl import HttpResponseImpl class ProgressTracker: @@ -32,34 +30,52 @@ def assert_complete(self): assert self.total == self.current -class MockHttpClientResponse(Response): - def __init__( - self, url: str, - body_bytes: bytes, - headers: Dict[str, Any], - status: int = 200, - reason: str = "OK" - ) -> None: - super(MockHttpClientResponse).__init__() - self._url = url - self._body = body_bytes - self._content = body_bytes - self._cache = {} - self._loop = None - self._content_consumed = True - self.headers = headers - self.status_code = status - self.reason = reason - self.raw = HTTPResponse() +def _mock_stream_generator(data: bytes): + """Simple generator that yields data in a single chunk.""" + + def generator(response, **kwargs): + yield data + + return generator + + +class _MockInternalResponse: + """Minimal internal response object for HttpResponseImpl.""" + + def close(self): + pass + + +def _make_rest_response( + request: HttpRequest, + body: bytes, + headers: Dict[str, Any], + status_code: int = 200, + reason: str = "OK", +) -> HttpResponseImpl: + """Create an azure.core.rest HttpResponse with iter_bytes/iter_raw support.""" + content_type = headers.get("Content-Type", "application/octet-stream") + resp = HttpResponseImpl( + request=request, + internal_response=_MockInternalResponse(), + status_code=status_code, + reason=reason, + content_type=content_type, + headers=headers, + stream_download_generator=_mock_stream_generator(body), + ) + resp._content = body # pylint: disable=protected-access + return resp class MockStorageTransport(HttpTransport): """ - This transport returns legacy http response objects from azure core and is - intended only to test our backwards compatibility support. + This transport returns azure.core.rest HttpResponse objects for + compatibility with TypeSpec-generated code that uses iter_bytes/iter_raw. """ - def send(self, request: HttpRequest, **kwargs: Any) -> RequestsTransportResponse: - if request.method == 'GET': + + def send(self, request: HttpRequest, **kwargs: Any) -> HttpResponseImpl: + if request.method == "GET": # download_file headers = { "Content-Type": "application/octet-stream", @@ -70,54 +86,34 @@ def send(self, request: HttpRequest, **kwargs: Any) -> RequestsTransportResponse if "x-ms-range-get-content-md5" in request.headers: headers["Content-MD5"] = "7Qdih1MuhjZehB6Sv8UNjA==" # cspell:disable-line - rest_response = RequestsTransportResponse( - request=request, - requests_response=MockHttpClientResponse( - request.url, - b"Hello World!", - headers, - ) - ) - elif request.method == 'HEAD': + rest_response = _make_rest_response(request, b"Hello World!", headers) + elif request.method == "HEAD": # get_file_properties - rest_response = RequestsTransportResponse( - request=request, - requests_response=MockHttpClientResponse( - request.url, - b"", - { - "Content-Type": "application/octet-stream", - "Content-Length": "1024", - }, - ) + rest_response = _make_rest_response( + request, + b"", + { + "Content-Type": "application/octet-stream", + "Content-Length": "1024", + }, ) - elif request.method == 'PUT': + elif request.method == "PUT": # upload_file - rest_response = RequestsTransportResponse( - request=request, - requests_response=MockHttpClientResponse( - request.url, - b"", - { - "Content-Length": "0", - }, - 201, - "Created" - ) + rest_response = _make_rest_response( + request, + b"", + {"Content-Length": "0"}, + 201, + "Created", ) - elif request.method == 'DELETE': + elif request.method == "DELETE": # delete_file - rest_response = RequestsTransportResponse( - request=request, - internal_response=MockHttpClientResponse( - request.url, - b"", - { - "Content-Length": "0", - }, - 202, - "Accepted" - ) + rest_response = _make_rest_response( + request, + b"", + {"Content-Length": "0"}, + 202, + "Accepted", ) else: raise ValueError("The request is not accepted as part of MockStorageTransport.") diff --git a/sdk/storage/azure-storage-file-share/tests/test_helpers_async.py b/sdk/storage/azure-storage-file-share/tests/test_helpers_async.py index 7f8fe5970760..3d5ef3a44ab5 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_helpers_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_helpers_async.py @@ -4,16 +4,11 @@ # license information. # -------------------------------------------------------------------------- -import asyncio -from collections import deque -from typing import Any, Dict, Optional +from typing import Any, AsyncIterator, Dict, Optional -from aiohttp import ClientResponse -from aiohttp.client_proto import ResponseHandler -from aiohttp.streams import StreamReader - -from azure.core.pipeline.transport import AioHttpTransportResponse, AsyncHttpTransport # pylint: disable=no-name-in-module +from azure.core.pipeline.transport import AsyncHttpTransport from azure.core.rest import HttpRequest +from azure.core.rest._http_response_impl_async import AsyncHttpResponseImpl class ProgressTracker: @@ -54,35 +49,52 @@ async def read(self, size: int = -1) -> bytes: return data -class MockAioHttpClientResponse(ClientResponse): - def __init__( - self, url: str, - body_bytes: bytes, - headers: Dict[str, Any], - status: int = 200, - reason: str = "OK" - ) -> None: - super(MockAioHttpClientResponse).__init__() - self._url = url - self._body = body_bytes - self._headers = headers - self._cache = {} - self._loop = None - self.status = status - self.reason = reason - self.content = StreamReader(ResponseHandler(asyncio.get_event_loop()), 65535) - self.content.total_bytes = len(body_bytes) - self.content._buffer = deque([body_bytes]) - self.content._eof = True +def _mock_async_stream_generator(data: bytes): + """Simple async generator that yields data in a single chunk.""" + + async def generator(response, **kwargs) -> AsyncIterator[bytes]: + yield data + + return generator + + +class _MockInternalResponse: + """Minimal internal response object for AsyncHttpResponseImpl.""" + + async def close(self): + pass + + +def _make_async_rest_response( + request: HttpRequest, + body: bytes, + headers: Dict[str, Any], + status_code: int = 200, + reason: str = "OK", +) -> AsyncHttpResponseImpl: + """Create an azure.core.rest async HttpResponse with iter_bytes/iter_raw support.""" + content_type = headers.get("Content-Type", "application/octet-stream") + resp = AsyncHttpResponseImpl( + request=request, + internal_response=_MockInternalResponse(), + status_code=status_code, + reason=reason, + content_type=content_type, + headers=headers, + stream_download_generator=_mock_async_stream_generator(body), + ) + resp._content = body # pylint: disable=protected-access + return resp class MockStorageTransport(AsyncHttpTransport): """ - This transport returns legacy http response objects from azure core and is - intended only to test our backwards compatibility support. + This transport returns azure.core.rest async HttpResponse objects for + compatibility with TypeSpec-generated code that uses iter_bytes/iter_raw. """ - async def send(self, request: HttpRequest, **kwargs: Any) -> AioHttpTransportResponse: - if request.method == 'GET': + + async def send(self, request: HttpRequest, **kwargs: Any) -> AsyncHttpResponseImpl: + if request.method == "GET": # download_file headers = { "Content-Type": "application/octet-stream", @@ -93,63 +105,37 @@ async def send(self, request: HttpRequest, **kwargs: Any) -> AioHttpTransportRes if "x-ms-range-get-content-md5" in request.headers: headers["Content-MD5"] = "I3pVbaOCUTom+G9F9uKFoA==" - rest_response = AioHttpTransportResponse( - request=request, - aiohttp_response=MockAioHttpClientResponse( - request.url, - b"Hello Async World!", - headers, - ), - decompress=False - ) - elif request.method == 'HEAD': + rest_response = _make_async_rest_response(request, b"Hello Async World!", headers) + elif request.method == "HEAD": # get_file_properties - rest_response = AioHttpTransportResponse( - request=request, - aiohttp_response=MockAioHttpClientResponse( - request.url, - b"", - { - "Content-Type": "application/octet-stream", - "Content-Length": "1024", - }, - ), - decompress=False + rest_response = _make_async_rest_response( + request, + b"", + { + "Content-Type": "application/octet-stream", + "Content-Length": "1024", + }, ) - elif request.method == 'PUT': + elif request.method == "PUT": # upload_file - rest_response = AioHttpTransportResponse( - request=request, - aiohttp_response=MockAioHttpClientResponse( - request.url, - b"", - { - "Content-Length": "0", - }, - 201, - "Created" - ), - decompress=False + rest_response = _make_async_rest_response( + request, + b"", + {"Content-Length": "0"}, + 201, + "Created", ) - elif request.method == 'DELETE': + elif request.method == "DELETE": # delete_file - rest_response = AioHttpTransportResponse( - request=request, - aiohttp_response=MockAioHttpClientResponse( - request.url, - b"", - { - "Content-Length": "0", - }, - 202, - "Accepted" - ), - decompress=False + rest_response = _make_async_rest_response( + request, + b"", + {"Content-Length": "0"}, + 202, + "Accepted", ) else: raise ValueError("The request is not accepted as part of MockStorageTransport.") - - await rest_response.load_body() return rest_response async def __aenter__(self): diff --git a/sdk/storage/azure-storage-file-share/tests/test_nfs.py b/sdk/storage/azure-storage-file-share/tests/test_nfs.py index 33b8a16159bf..be0067dcb8c6 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_nfs.py +++ b/sdk/storage/azure-storage-file-share/tests/test_nfs.py @@ -3,30 +3,32 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- - +import pytest from typing import Any, Dict, Optional, Union from urllib.parse import unquote -import pytest - -from devtools_testutils import recorded_by_proxy -from devtools_testutils.storage import StorageRecordedTestCase -from settings.testcase import FileSharePreparer - -from azure.core.exceptions import ResourceNotFoundError +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, +) from azure.storage.fileshare import ( ContentSettings, - DirectoryProperties, FileProperties, - ShareDirectoryClient, + DirectoryProperties, ShareFileClient, + ShareDirectoryClient, ShareServiceClient, ) +from devtools_testutils import recorded_by_proxy +from devtools_testutils.storage import StorageRecordedTestCase +from settings.testcase import FileSharePreparer -TEST_INTENT = 'backup' -TEST_FILE_PREFIX = 'file' -TEST_DIRECTORY_PREFIX = 'directory' +TEST_INTENT = "backup" +TEST_FILE_PREFIX = "file" +TEST_DIRECTORY_PREFIX = "directory" class TestStorageFileNFS(StorageRecordedTestCase): @@ -34,17 +36,15 @@ class TestStorageFileNFS(StorageRecordedTestCase): fsc: ShareServiceClient = None def _setup(self, storage_account_name: str): - self.account_url = self.account_url(storage_account_name, 'file') + self.account_url = self.account_url(storage_account_name, "file") self.credential = self.get_credential(ShareServiceClient) self.fsc = ShareServiceClient( - account_url=self.account_url, - credential=self.credential, - token_intent=TEST_INTENT + account_url=self.account_url, credential=self.credential, token_intent=TEST_INTENT ) - self.share_name = self.get_resource_name('utshare') + self.share_name = self.get_resource_name("utshare") if self.is_live: try: - self.fsc.create_share(self.share_name, protocols='NFS') + self.fsc.create_share(self.share_name, protocols="NFS") except: pass @@ -63,11 +63,12 @@ def _get_directory_name(self, prefix: str = TEST_DIRECTORY_PREFIX): return self.get_resource_name(prefix) def _assert_props( - self, props: Optional[Union[DirectoryProperties, FileProperties]], + self, + props: Optional[Union[DirectoryProperties, FileProperties]], owner: str, group: str, file_mode: str, - nfs_file_type: Optional[str] = None + nfs_file_type: Optional[str] = None, ) -> None: assert props is not None assert props.owner == owner @@ -83,8 +84,8 @@ def _assert_props( def _assert_copy(self, copy: Optional[Dict[str, Any]]) -> None: assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None # --Test cases for NFS ---------------------------------------------- @FileSharePreparer() @@ -94,24 +95,21 @@ def test_create_directory_and_set_directory_properties(self, **kwargs: Any): self._setup(premium_storage_file_account_name) - create_owner, create_group, create_file_mode = '345', '123', '7777' - set_owner, set_group, set_file_mode = '0', '0', '0755' + create_owner, create_group, create_file_mode = "345", "123", "7777" + set_owner, set_group, set_file_mode = "0", "0", "0755" share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url, - share_client.share_name, 'dir1', - credential=self.credential, - token_intent=TEST_INTENT + self.account_url, share_client.share_name, "dir1", credential=self.credential, token_intent=TEST_INTENT ) directory_client.create_directory(owner=create_owner, group=create_group, file_mode=create_file_mode) props = directory_client.get_directory_properties() - self._assert_props(props, create_owner, create_group, create_file_mode, 'Directory') + self._assert_props(props, create_owner, create_group, create_file_mode, "Directory") directory_client.set_http_headers(owner=set_owner, group=set_group, file_mode=set_file_mode) props = directory_client.get_directory_properties() - self._assert_props(props, set_owner, set_group, set_file_mode, 'Directory') + self._assert_props(props, set_owner, set_group, set_file_mode, "Directory") @FileSharePreparer() @recorded_by_proxy @@ -126,28 +124,22 @@ def test_create_file_and_set_file_properties(self, **kwargs: Any): share_name=self.share_name, file_path=file_name, credential=self.credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) - create_owner, create_group, create_file_mode = '345', '123', '7777' - set_owner, set_group, set_file_mode = '0', '0', '0644' - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline' - ) + create_owner, create_group, create_file_mode = "345", "123", "7777" + set_owner, set_group, set_file_mode = "0", "0", "0644" + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") file_client.create_file(1024, owner=create_owner, group=create_group, file_mode=create_file_mode) props = file_client.get_file_properties() - self._assert_props(props, create_owner, create_group, create_file_mode, 'Regular') + self._assert_props(props, create_owner, create_group, create_file_mode, "Regular") file_client.set_http_headers( - content_settings=content_settings, - owner=set_owner, - group=set_group, - file_mode=set_file_mode + content_settings=content_settings, owner=set_owner, group=set_group, file_mode=set_file_mode ) props = file_client.get_file_properties() - self._assert_props(props, set_owner, set_group, set_file_mode, 'Regular') + self._assert_props(props, set_owner, set_group, set_file_mode, "Regular") @FileSharePreparer() @recorded_by_proxy @@ -156,10 +148,10 @@ def test_download_and_copy_file(self, **kwargs: Any): self._setup(premium_storage_file_account_name) - default_owner, default_group, default_file_mode = '0', '0', '0664' - source_owner, source_group, source_file_mode = '999', '888', '0111' - override_owner, override_group, override_file_mode = '54321', '12345', '7777' - data = b'abcdefghijklmnop' * 32 + default_owner, default_group, default_file_mode = "0", "0", "0664" + source_owner, source_group, source_file_mode = "999", "888", "0111" + override_owner, override_group, override_file_mode = "54321", "12345", "7777" + data = b"abcdefghijklmnop" * 32 share_client = self.fsc.get_share_client(self.share_name) @@ -174,14 +166,12 @@ def test_download_and_copy_file(self, **kwargs: Any): new_client_source_copy = ShareFileClient( self.account_url, share_name=self.share_name, - file_path='newclientsourcecopy', + file_path="newclientsourcecopy", credential=self.credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) copy = new_client_source_copy.start_copy_from_url( - file_client.url, - file_mode_copy_mode='source', - owner_copy_mode='source' + file_client.url, file_mode_copy_mode="source", owner_copy_mode="source" ) self._assert_copy(copy) props = new_client_source_copy.get_file_properties() @@ -190,9 +180,9 @@ def test_download_and_copy_file(self, **kwargs: Any): new_client_default_copy = ShareFileClient( self.account_url, share_name=self.share_name, - file_path='newclientdefaultcopy', + file_path="newclientdefaultcopy", credential=self.credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) copy = new_client_default_copy.start_copy_from_url(file_client.url) self._assert_copy(copy) @@ -202,17 +192,17 @@ def test_download_and_copy_file(self, **kwargs: Any): new_client_override_copy = ShareFileClient( self.account_url, share_name=self.share_name, - file_path='newclientoverridecopy', + file_path="newclientoverridecopy", credential=self.credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) copy = new_client_override_copy.start_copy_from_url( file_client.url, owner=override_owner, group=override_group, file_mode=override_file_mode, - file_mode_copy_mode='override', - owner_copy_mode='override' + file_mode_copy_mode="override", + owner_copy_mode="override", ) self._assert_copy(copy) props = new_client_override_copy.get_file_properties() @@ -228,29 +218,29 @@ def test_create_hardlink(self, **kwargs: Any): share_client = self.fsc.get_share_client(self.share_name) directory_name = self._get_directory_name() directory_client = share_client.create_directory(directory_name) - source_file_name = self._get_file_name('file1') + source_file_name = self._get_file_name("file1") source_file_client = directory_client.get_file_client(source_file_name) source_file_client.create_file(size=1024) - hard_link_file_name = self._get_file_name('file2') + hard_link_file_name = self._get_file_name("file2") hard_link_file_client = directory_client.get_file_client(hard_link_file_name) resp = hard_link_file_client.create_hardlink(target=f"{directory_name}/{source_file_name}") assert resp is not None - assert resp['file_file_type'] == 'Regular' - assert resp['owner'] == '0' - assert resp['group'] == '0' - assert resp['mode'] == '0664' - assert resp['link_count'] == 2 + assert resp["file_file_type"] == "Regular" + assert resp["owner"] == "0" + assert resp["group"] == "0" + assert resp["mode"] == "0664" + assert resp["link_count"] == 2 - assert resp['file_creation_time'] is not None - assert resp['file_last_write_time'] is not None - assert resp['file_change_time'] is not None - assert resp['file_id'] is not None - assert resp['file_parent_id'] is not None + assert resp["file_creation_time"] is not None + assert resp["file_last_write_time"] is not None + assert resp["file_change_time"] is not None + assert resp["file_id"] is not None + assert resp["file_parent_id"] is not None - assert 'file_attributes' not in resp - assert 'file_response_key' not in resp + assert "file_attributes" not in resp + assert "file_response_key" not in resp @FileSharePreparer() @recorded_by_proxy @@ -262,15 +252,15 @@ def test_create_hardlink_error(self, **kwargs: Any): share_client = self.fsc.get_share_client(self.share_name) directory_name = self._get_directory_name() directory_client = share_client.get_directory_client(directory_name) - source_file_name = self._get_file_name('file1') + source_file_name = self._get_file_name("file1") source_file_client = directory_client.get_file_client(source_file_name) - hard_link_file_name = self._get_file_name('file2') + hard_link_file_name = self._get_file_name("file2") hard_link_file_client = directory_client.get_file_client(hard_link_file_name) with pytest.raises(ResourceNotFoundError) as e: hard_link_file_client.create_hardlink(target=f"{directory_name}/{source_file_name}") - assert 'ParentNotFound' in e.value.args[0] + assert "ParentNotFound" in e.value.args[0] @FileSharePreparer() @recorded_by_proxy @@ -282,37 +272,32 @@ def test_create_and_get_symlink(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_name = self._get_directory_name() directory_client = share_client.create_directory(directory_name) - source_file_name = self._get_file_name('file1') + source_file_name = self._get_file_name("file1") source_file_client = directory_client.get_file_client(source_file_name) source_file_client.create_file(size=1024) - symbolic_link_file_name = self._get_file_name('file2') + symbolic_link_file_name = self._get_file_name("file2") symbolic_link_file_client = directory_client.get_file_client(symbolic_link_file_name) metadata = {"test1": "foo", "test2": "bar"} owner, group = "345", "123" target = f"{directory_name}/{source_file_name}" - resp = symbolic_link_file_client.create_symlink( - target=target, - metadata=metadata, - owner=owner, - group=group - ) + resp = symbolic_link_file_client.create_symlink(target=target, metadata=metadata, owner=owner, group=group) assert resp is not None - assert resp['file_file_type'] == 'SymLink' - assert resp['owner'] == owner - assert resp['group'] == group - assert resp['file_creation_time'] is not None - assert resp['file_last_write_time'] is not None - assert resp['file_id'] is not None - assert resp['file_parent_id'] is not None - assert 'file_attributes' not in resp - assert 'file_permission_key' not in resp + assert resp["file_file_type"] == "SymLink" + assert resp["owner"] == owner + assert resp["group"] == group + assert resp["file_creation_time"] is not None + assert resp["file_last_write_time"] is not None + assert resp["file_id"] is not None + assert resp["file_parent_id"] is not None + assert "file_attributes" not in resp + assert "file_permission_key" not in resp resp = symbolic_link_file_client.get_symlink() assert resp is not None - assert resp['etag'] is not None - assert resp['last_modified'] is not None - assert unquote(resp['link_text']) == target + assert resp["etag"] is not None + assert resp["last_modified"] is not None + assert unquote(resp["link_text"]) == target @FileSharePreparer() @recorded_by_proxy @@ -324,16 +309,16 @@ def test_create_and_get_symlink_error(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_name = self._get_directory_name() directory_client = share_client.get_directory_client(directory_name) - source_file_name = self._get_file_name('file1') + source_file_name = self._get_file_name("file1") source_file_client = directory_client.get_file_client(source_file_name) - symbolic_link_file_name = self._get_file_name('file2') + symbolic_link_file_name = self._get_file_name("file2") symbolic_link_file_client = directory_client.get_file_client(symbolic_link_file_name) target = f"{directory_name}/{source_file_name}" with pytest.raises(ResourceNotFoundError) as e: symbolic_link_file_client.create_symlink(target=target) - assert 'ParentNotFound' in e.value.args[0] + assert "ParentNotFound" in e.value.args[0] with pytest.raises(ResourceNotFoundError) as e: symbolic_link_file_client.get_symlink() - assert 'ParentNotFound' in e.value.args[0] + assert "ParentNotFound" in e.value.args[0] diff --git a/sdk/storage/azure-storage-file-share/tests/test_nfs_async.py b/sdk/storage/azure-storage-file-share/tests/test_nfs_async.py index 3f368e15b851..961da25149ba 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_nfs_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_nfs_async.py @@ -3,30 +3,28 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- - +import pytest from typing import Any, Dict, Optional, Union from urllib.parse import unquote -import pytest +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, +) +from azure.storage.fileshare import ContentSettings, DirectoryProperties, FileProperties, ShareServiceClient +from azure.storage.fileshare.aio import ShareServiceClient as AsyncShareServiceClient +from azure.storage.fileshare.aio import ShareFileClient, ShareDirectoryClient from devtools_testutils.aio import recorded_by_proxy_async from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase from settings.testcase import FileSharePreparer -from azure.core.exceptions import ResourceNotFoundError -from azure.storage.fileshare import ( - ContentSettings, - DirectoryProperties, - FileProperties, - ShareServiceClient, -) -from azure.storage.fileshare.aio import ShareDirectoryClient, ShareFileClient -from azure.storage.fileshare.aio import ShareServiceClient as AsyncShareServiceClient - -TEST_INTENT = 'backup' -TEST_FILE_PREFIX = 'file' -TEST_DIRECTORY_PREFIX = 'directory' +TEST_INTENT = "backup" +TEST_FILE_PREFIX = "file" +TEST_DIRECTORY_PREFIX = "directory" class TestStorageFileNFSAsync(AsyncStorageRecordedTestCase): @@ -34,23 +32,19 @@ class TestStorageFileNFSAsync(AsyncStorageRecordedTestCase): fsc: AsyncShareServiceClient = None async def _setup(self, storage_account_name: str): - self.account_url = self.account_url(storage_account_name, 'file') + self.account_url = self.account_url(storage_account_name, "file") self.credential = self.get_credential(AsyncShareServiceClient, is_async=True) self.fsc = AsyncShareServiceClient( - account_url=self.account_url, - credential=self.credential, - token_intent=TEST_INTENT + account_url=self.account_url, credential=self.credential, token_intent=TEST_INTENT ) - self.share_name = self.get_resource_name('utshare') + self.share_name = self.get_resource_name("utshare") async with AsyncShareServiceClient( - account_url=self.account_url, - credential=self.credential, - token_intent=TEST_INTENT + account_url=self.account_url, credential=self.credential, token_intent=TEST_INTENT ) as fsc: if self.is_live: try: - await fsc.create_share(self.share_name, protocols='NFS') + await fsc.create_share(self.share_name, protocols="NFS") except: pass @@ -60,7 +54,7 @@ def teardown_method(self): fsc = ShareServiceClient( account_url=self.account_url, credential=self.get_credential(ShareServiceClient), - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) fsc.delete_share(self.share_name) except: @@ -74,11 +68,12 @@ def _get_directory_name(self, prefix: str = TEST_DIRECTORY_PREFIX): return self.get_resource_name(prefix) def _assert_props( - self, props: Optional[Union[DirectoryProperties, FileProperties]], + self, + props: Optional[Union[DirectoryProperties, FileProperties]], owner: str, group: str, file_mode: str, - nfs_file_type: Optional[str] = None + nfs_file_type: Optional[str] = None, ) -> None: assert props is not None assert props.owner == owner @@ -94,8 +89,8 @@ def _assert_props( def _assert_copy(self, copy: Optional[Dict[str, Any]]) -> None: assert copy is not None - assert copy['copy_status'] == 'success' - assert copy['copy_id'] is not None + assert copy["copy_status"] == "success" + assert copy["copy_id"] is not None # --Test cases for NFS ---------------------------------------------- @FileSharePreparer() @@ -105,24 +100,21 @@ async def test_create_directory_and_set_directory_properties(self, **kwargs: Any await self._setup(premium_storage_file_account_name) - create_owner, create_group, create_file_mode = '345', '123', '7777' - set_owner, set_group, set_file_mode = '0', '0', '0755' + create_owner, create_group, create_file_mode = "345", "123", "7777" + set_owner, set_group, set_file_mode = "0", "0", "0755" share_client = self.fsc.get_share_client(self.share_name) directory_client = ShareDirectoryClient( - self.account_url, - share_client.share_name, 'dir1', - credential=self.credential, - token_intent=TEST_INTENT + self.account_url, share_client.share_name, "dir1", credential=self.credential, token_intent=TEST_INTENT ) await directory_client.create_directory(owner=create_owner, group=create_group, file_mode=create_file_mode) props = await directory_client.get_directory_properties() - self._assert_props(props, create_owner, create_group, create_file_mode, 'Directory') + self._assert_props(props, create_owner, create_group, create_file_mode, "Directory") await directory_client.set_http_headers(owner=set_owner, group=set_group, file_mode=set_file_mode) props = await directory_client.get_directory_properties() - self._assert_props(props, set_owner, set_group, set_file_mode, 'Directory') + self._assert_props(props, set_owner, set_group, set_file_mode, "Directory") @FileSharePreparer() @recorded_by_proxy_async @@ -137,28 +129,22 @@ async def test_create_file_and_set_file_properties(self, **kwargs: Any): share_name=self.share_name, file_path=file_name, credential=self.credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) - create_owner, create_group, create_file_mode = '345', '123', '7777' - set_owner, set_group, set_file_mode = '0', '0', '0644' - content_settings = ContentSettings( - content_language='spanish', - content_disposition='inline' - ) + create_owner, create_group, create_file_mode = "345", "123", "7777" + set_owner, set_group, set_file_mode = "0", "0", "0644" + content_settings = ContentSettings(content_language="spanish", content_disposition="inline") await file_client.create_file(1024, owner=create_owner, group=create_group, file_mode=create_file_mode) props = await file_client.get_file_properties() - self._assert_props(props, create_owner, create_group, create_file_mode, 'Regular') + self._assert_props(props, create_owner, create_group, create_file_mode, "Regular") await file_client.set_http_headers( - content_settings=content_settings, - owner=set_owner, - group=set_group, - file_mode=set_file_mode + content_settings=content_settings, owner=set_owner, group=set_group, file_mode=set_file_mode ) props = await file_client.get_file_properties() - self._assert_props(props, set_owner, set_group, set_file_mode, 'Regular') + self._assert_props(props, set_owner, set_group, set_file_mode, "Regular") @FileSharePreparer() @recorded_by_proxy_async @@ -167,10 +153,10 @@ async def test_download_and_copy_file(self, **kwargs: Any): await self._setup(premium_storage_file_account_name) - default_owner, default_group, default_file_mode = '0', '0', '0664' - source_owner, source_group, source_file_mode = '999', '888', '0111' - override_owner, override_group, override_file_mode = '54321', '12345', '7777' - data = b'abcdefghijklmnop' * 32 + default_owner, default_group, default_file_mode = "0", "0", "0664" + source_owner, source_group, source_file_mode = "999", "888", "0111" + override_owner, override_group, override_file_mode = "54321", "12345", "7777" + data = b"abcdefghijklmnop" * 32 share_client = self.fsc.get_share_client(self.share_name) @@ -185,14 +171,12 @@ async def test_download_and_copy_file(self, **kwargs: Any): new_client_source_copy = ShareFileClient( self.account_url, share_name=self.share_name, - file_path='newclientsourcecopy', + file_path="newclientsourcecopy", credential=self.credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) copy = await new_client_source_copy.start_copy_from_url( - file_client.url, - file_mode_copy_mode='source', - owner_copy_mode='source' + file_client.url, file_mode_copy_mode="source", owner_copy_mode="source" ) self._assert_copy(copy) props = await new_client_source_copy.get_file_properties() @@ -201,9 +185,9 @@ async def test_download_and_copy_file(self, **kwargs: Any): new_client_default_copy = ShareFileClient( self.account_url, share_name=self.share_name, - file_path='newclientdefaultcopy', + file_path="newclientdefaultcopy", credential=self.credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) copy = await new_client_default_copy.start_copy_from_url(file_client.url) self._assert_copy(copy) @@ -213,17 +197,17 @@ async def test_download_and_copy_file(self, **kwargs: Any): new_client_override_copy = ShareFileClient( self.account_url, share_name=self.share_name, - file_path='newclientoverridecopy', + file_path="newclientoverridecopy", credential=self.credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) copy = await new_client_override_copy.start_copy_from_url( file_client.url, owner=override_owner, group=override_group, file_mode=override_file_mode, - file_mode_copy_mode='override', - owner_copy_mode='override' + file_mode_copy_mode="override", + owner_copy_mode="override", ) self._assert_copy(copy) props = await new_client_override_copy.get_file_properties() @@ -239,29 +223,29 @@ async def test_create_hardlink(self, **kwargs: Any): share_client = self.fsc.get_share_client(self.share_name) directory_name = self._get_directory_name() directory_client = await share_client.create_directory(directory_name) - source_file_name = self._get_file_name('file1') + source_file_name = self._get_file_name("file1") source_file_client = directory_client.get_file_client(source_file_name) await source_file_client.create_file(size=1024) - hard_link_file_name = self._get_file_name('file2') + hard_link_file_name = self._get_file_name("file2") hard_link_file_client = directory_client.get_file_client(hard_link_file_name) resp = await hard_link_file_client.create_hardlink(target=f"{directory_name}/{source_file_name}") assert resp is not None - assert resp['file_file_type'] == 'Regular' - assert resp['owner'] == '0' - assert resp['group'] == '0' - assert resp['mode'] == '0664' - assert resp['link_count'] == 2 + assert resp["file_file_type"] == "Regular" + assert resp["owner"] == "0" + assert resp["group"] == "0" + assert resp["mode"] == "0664" + assert resp["link_count"] == 2 - assert resp['file_creation_time'] is not None - assert resp['file_last_write_time'] is not None - assert resp['file_change_time'] is not None - assert resp['file_id'] is not None - assert resp['file_parent_id'] is not None + assert resp["file_creation_time"] is not None + assert resp["file_last_write_time"] is not None + assert resp["file_change_time"] is not None + assert resp["file_id"] is not None + assert resp["file_parent_id"] is not None - assert 'file_attributes' not in resp - assert 'file_response_key' not in resp + assert "file_attributes" not in resp + assert "file_response_key" not in resp @FileSharePreparer() @recorded_by_proxy_async @@ -273,15 +257,15 @@ async def test_create_hardlink_error(self, **kwargs: Any): share_client = self.fsc.get_share_client(self.share_name) directory_name = self._get_directory_name() directory_client = share_client.get_directory_client(directory_name) - source_file_name = self._get_file_name('file1') + source_file_name = self._get_file_name("file1") source_file_client = directory_client.get_file_client(source_file_name) - hard_link_file_name = self._get_file_name('file2') + hard_link_file_name = self._get_file_name("file2") hard_link_file_client = directory_client.get_file_client(hard_link_file_name) with pytest.raises(ResourceNotFoundError) as e: await hard_link_file_client.create_hardlink(target=f"{directory_name}/{source_file_name}") - assert 'ParentNotFound' in e.value.args[0] + assert "ParentNotFound" in e.value.args[0] @FileSharePreparer() @recorded_by_proxy_async @@ -293,37 +277,34 @@ async def test_create_and_get_symlink(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_name = self._get_directory_name() directory_client = await share_client.create_directory(directory_name) - source_file_name = self._get_file_name('file1') + source_file_name = self._get_file_name("file1") source_file_client = directory_client.get_file_client(source_file_name) await source_file_client.create_file(size=1024) - symbolic_link_file_name = self._get_file_name('file2') + symbolic_link_file_name = self._get_file_name("file2") symbolic_link_file_client = directory_client.get_file_client(symbolic_link_file_name) metadata = {"test1": "foo", "test2": "bar"} owner, group = "345", "123" target = f"{directory_name}/{source_file_name}" resp = await symbolic_link_file_client.create_symlink( - target=target, - metadata=metadata, - owner=owner, - group=group + target=target, metadata=metadata, owner=owner, group=group ) assert resp is not None - assert resp['file_file_type'] == 'SymLink' - assert resp['owner'] == owner - assert resp['group'] == group - assert resp['file_creation_time'] is not None - assert resp['file_last_write_time'] is not None - assert resp['file_id'] is not None - assert resp['file_parent_id'] is not None - assert 'file_attributes' not in resp - assert 'file_permission_key' not in resp + assert resp["file_file_type"] == "SymLink" + assert resp["owner"] == owner + assert resp["group"] == group + assert resp["file_creation_time"] is not None + assert resp["file_last_write_time"] is not None + assert resp["file_id"] is not None + assert resp["file_parent_id"] is not None + assert "file_attributes" not in resp + assert "file_permission_key" not in resp resp = await symbolic_link_file_client.get_symlink() assert resp is not None - assert resp['etag'] is not None - assert resp['last_modified'] is not None - assert unquote(resp['link_text']) == target + assert resp["etag"] is not None + assert resp["last_modified"] is not None + assert unquote(resp["link_text"]) == target @FileSharePreparer() @recorded_by_proxy_async @@ -335,16 +316,16 @@ async def test_create_and_get_symlink_error(self, **kwargs): share_client = self.fsc.get_share_client(self.share_name) directory_name = self._get_directory_name() directory_client = share_client.get_directory_client(directory_name) - source_file_name = self._get_file_name('file1') + source_file_name = self._get_file_name("file1") source_file_client = directory_client.get_file_client(source_file_name) - symbolic_link_file_name = self._get_file_name('file2') + symbolic_link_file_name = self._get_file_name("file2") symbolic_link_file_client = directory_client.get_file_client(symbolic_link_file_name) target = f"{directory_name}/{source_file_name}" with pytest.raises(ResourceNotFoundError) as e: await symbolic_link_file_client.create_symlink(target=target) - assert 'ParentNotFound' in e.value.args[0] + assert "ParentNotFound" in e.value.args[0] with pytest.raises(ResourceNotFoundError) as e: await symbolic_link_file_client.get_symlink() - assert 'ParentNotFound' in e.value.args[0] + assert "ParentNotFound" in e.value.args[0] diff --git a/sdk/storage/azure-storage-file-share/tests/test_share.py b/sdk/storage/azure-storage-file-share/tests/test_share.py index a51e1f0b3878..0360f5367625 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_share.py +++ b/sdk/storage/azure-storage-file-share/tests/test_share.py @@ -1,29 +1,24 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- - +import jwt import os import time import unittest from datetime import datetime, timedelta -import jwt import pytest import requests - -from devtools_testutils import recorded_by_proxy -from devtools_testutils.storage import LogCaptured, StorageRecordedTestCase -from settings.testcase import FileSharePreparer - from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ) -from azure.core.pipeline.transport import RequestsTransport # pylint: disable=no-name-in-module +from azure.core.pipeline.transport import RequestsTransport from azure.storage.fileshare import ( AccessPolicy, AccountSasPermissions, @@ -31,7 +26,9 @@ generate_account_sas, generate_file_sas, generate_share_sas, + Metrics, ResourceTypes, + RetentionPolicy, ShareAccessTier, ShareClient, ShareFileClient, @@ -42,12 +39,16 @@ StorageErrorCode, ) +from devtools_testutils import recorded_by_proxy +from devtools_testutils.storage import LogCaptured, StorageRecordedTestCase +from settings.testcase import FileSharePreparer # ------------------------------------------------------------------------------ -TEST_SHARE_PREFIX = 'share' +TEST_SHARE_PREFIX = "share" TEST_INTENT = "backup" # ------------------------------------------------------------------------------ + class TestStorageShare(StorageRecordedTestCase): def _setup(self, storage_account_name, storage_account_key): file_url = self.account_url(storage_account_name, "file") @@ -61,6 +62,7 @@ def _teardown(self, FILE_PATH): os.remove(FILE_PATH) except: pass + # --Helpers----------------------------------------------------------------- def _get_share_reference(self, prefix=TEST_SHARE_PREFIX): share_name = self.get_resource_name(prefix) @@ -76,29 +78,28 @@ def _create_share(self, prefix=TEST_SHARE_PREFIX, **kwargs): pass return share_client + def _create_share_if_not_exists(self, prefix=TEST_SHARE_PREFIX, **kwargs): + share_client = self._get_share_reference(prefix) + return share_client.create_share_if_not_exists(**kwargs) + def _delete_shares(self, prefix=TEST_SHARE_PREFIX): for l in self.fsc.list_shares(include_snapshots=True): - if l.name.startswith(prefix): - try: - self.fsc.delete_share(l.name, delete_snapshots=True) - except: - pass + try: + self.fsc.delete_share(l.name, delete_snapshots=True) + except: + pass # --Test cases for shares ----------------------------------------- def test_create_share_client(self): share_client = ShareClient.from_share_url( "http://127.0.0.1:11002/account/customized/path/share?snapshot=baz&", - credential={ - "account_name": "myaccount", - "account_key": "key" - } + credential={"account_name": "myaccount", "account_key": "key"}, ) assert share_client.share_name == "share" assert share_client.snapshot == "baz" share_client = ShareClient.from_share_url( - "http://127.0.0.1:11002/account/share?snapshot=baz&", - credential="credential" + "http://127.0.0.1:11002/account/share?snapshot=baz&", credential="credential" ) assert share_client.share_name == "share" assert share_client.snapshot == "baz" @@ -135,7 +136,7 @@ def test_create_share_with_oauth_fails(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=share_name, credential=token_credential, - file_request_intent=TEST_INTENT + file_request_intent=TEST_INTENT, ) @FileSharePreparer() @@ -153,9 +154,9 @@ def test_create_share_snapshot(self, **kwargs): # Assert assert created - assert snapshot['snapshot'] is not None - assert snapshot['etag'] is not None - assert snapshot['last_modified'] is not None + assert snapshot["snapshot"] is not None + assert snapshot["etag"] is not None + assert snapshot["last_modified"] is not None self._delete_shares(share.share_name) @FileSharePreparer() @@ -178,14 +179,14 @@ def test_create_snapshot_with_metadata(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=share.share_name, snapshot=snapshot, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) snapshot_props = snapshot_client.get_share_properties() # Assert assert created - assert snapshot['snapshot'] is not None - assert snapshot['etag'] is not None - assert snapshot['last_modified'] is not None + assert snapshot["snapshot"] is not None + assert snapshot["etag"] is not None + assert snapshot["last_modified"] is not None assert share_props.metadata == metadata assert snapshot_props.metadata == metadata2 self._delete_shares(share.share_name) @@ -228,9 +229,9 @@ def test_lease_share_acquire_and_release(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') + share_client = self._create_share("test") # Act - lease = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") lease.release() # Assert @@ -251,11 +252,11 @@ def test_acquire_lease_on_sharesnapshot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=share.share_name, snapshot=snapshot, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) - share_lease = share.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') - share_snapshot_lease = snapshot_client.acquire_lease(lease_id='44444444-3333-2222-1111-000000000000') + share_lease = share.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") + share_snapshot_lease = snapshot_client.acquire_lease(lease_id="44444444-3333-2222-1111-000000000000") # Assert with pytest.raises(HttpResponseError): @@ -264,9 +265,9 @@ def test_acquire_lease_on_sharesnapshot(self, **kwargs): with pytest.raises(HttpResponseError): snapshot_client.get_share_properties(lease=share_lease) - assert snapshot['snapshot'] is not None - assert snapshot['etag'] is not None - assert snapshot['last_modified'] is not None + assert snapshot["snapshot"] is not None + assert snapshot["etag"] is not None + assert snapshot["last_modified"] is not None assert share_lease is not None assert share_snapshot_lease is not None assert share_lease != share_snapshot_lease @@ -282,8 +283,8 @@ def test_lease_share_renew(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') - lease = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + share_client = self._create_share("test") + lease = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) self.sleep(10) lease_id_start = lease.id @@ -305,16 +306,16 @@ def test_lease_share_with_duration(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test1') + share_client = self._create_share("test1") # Act - lease = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + lease = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) # Assert with pytest.raises(HttpResponseError): - share_client.acquire_lease(lease_id='44444444-3333-2222-1111-000000000000') + share_client.acquire_lease(lease_id="44444444-3333-2222-1111-000000000000") self.sleep(17) - share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") @FileSharePreparer() @recorded_by_proxy @@ -323,10 +324,10 @@ def test_lease_share_twice(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') + share_client = self._create_share("test") # Act - lease = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + lease = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) # Assert lease2 = share_client.acquire_lease(lease_id=lease.id) @@ -339,10 +340,10 @@ def test_lease_share_with_proposed_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') + share_client = self._create_share("test") # Act - proposed_lease_id = '55e97f64-73e8-4390-838d-d9e84a374321' + proposed_lease_id = "55e97f64-73e8-4390-838d-d9e84a374321" lease = share_client.acquire_lease(lease_id=proposed_lease_id) # Assert @@ -355,11 +356,11 @@ def test_lease_share_change_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') + share_client = self._create_share("test") # Act - lease_id = '29e0b239-ecda-4f69-bfa3-95f6af91464c' - lease = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease_id = "29e0b239-ecda-4f69-bfa3-95f6af91464c" + lease = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") lease_id1 = lease.id lease.change(proposed_lease_id=lease_id) lease.renew() @@ -378,9 +379,9 @@ def test_set_share_metadata_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') - metadata = {'hello': 'world', 'number': '43'} - lease_id = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share_client = self._create_share("test") + metadata = {"hello": "world", "number": "43"} + lease_id = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act share_client.set_share_metadata(metadata, lease=lease_id) @@ -396,10 +397,10 @@ def test_get_share_metadata_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') - metadata = {'hello': 'world', 'number': '43'} + share_client = self._create_share("test") + metadata = {"hello": "world", "number": "43"} share_client.set_share_metadata(metadata) - lease_id = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease_id = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act md = share_client.get_share_properties(lease=lease_id).metadata @@ -414,10 +415,10 @@ def test_get_share_properties_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') - metadata = {'hello': 'world', 'number': '43'} + share_client = self._create_share("test") + metadata = {"hello": "world", "number": "43"} share_client.set_share_metadata(metadata) - lease_id = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease_id = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act props = share_client.get_share_properties(lease=lease_id) @@ -426,9 +427,9 @@ def test_get_share_properties_with_lease_id(self, **kwargs): # Assert assert props is not None assert props.metadata == metadata - assert props.lease.duration == 'infinite' - assert props.lease.state == 'leased' - assert props.lease.status == 'locked' + assert props.lease.duration == "infinite" + assert props.lease.state == "leased" + assert props.lease.status == "locked" @FileSharePreparer() @recorded_by_proxy @@ -437,41 +438,39 @@ def test_get_share_acl_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') - lease_id = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share_client = self._create_share("test") + lease_id = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act acl = share_client.get_share_access_policy(lease=lease_id) # Assert assert acl is not None - assert acl.get('public_access') is None + assert acl.get("public_access") is None @FileSharePreparer() @recorded_by_proxy def test_set_share_acl_with_lease_id(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - variables = kwargs.pop('variables', {}) + variables = kwargs.pop("variables", {}) self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') - lease_id = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share_client = self._create_share("test") + lease_id = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act - expiry_time = self.get_datetime_variable(variables, 'expiry_time', datetime.utcnow() + timedelta(hours=1)) - start_time = self.get_datetime_variable(variables, 'start_time', datetime.utcnow()) - access_policy = AccessPolicy(permission=ShareSasPermissions(read=True), - expiry=expiry_time, - start=start_time) - signed_identifiers = {'testid': access_policy} + expiry_time = self.get_datetime_variable(variables, "expiry_time", datetime.utcnow() + timedelta(hours=1)) + start_time = self.get_datetime_variable(variables, "start_time", datetime.utcnow()) + access_policy = AccessPolicy(permission=ShareSasPermissions(read=True), expiry=expiry_time, start=start_time) + signed_identifiers = {"testid": access_policy} share_client.set_share_access_policy(signed_identifiers, lease=lease_id) # Assert acl = share_client.get_share_access_policy() assert acl is not None - assert acl.get('public_access') is None + assert acl.get("public_access") is None return variables @@ -482,10 +481,10 @@ def test_lease_share_break_period(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') + share_client = self._create_share("test") # Act - lease = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + lease = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) # Assert lease.break_lease(lease_break_period=5) @@ -500,8 +499,8 @@ def test_delete_share_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = self._create_share('test') - lease = share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + share_client = self._create_share("test") + lease = share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) # Assert with pytest.raises(HttpResponseError): @@ -564,7 +563,7 @@ def test_delete_snapshot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=share.share_name, snapshot=snapshot, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) deleted = snapshot_client.delete_share() @@ -612,7 +611,7 @@ def test_create_share_with_metadata(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act client = self._get_share_reference() @@ -718,7 +717,7 @@ def test_share_snapshot_not_exists(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = self._create_share() - made_up_snapshot = '2017-07-19T06:53:46.0000000Z' + made_up_snapshot = "2017-07-19T06:53:46.0000000Z" # Act snapshot_client = self.fsc.get_share_client(share.share_name, snapshot=made_up_snapshot) @@ -735,7 +734,7 @@ def test_unicode_create_share_unicode_name(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_name = '啊齄丂狛狜' + share_name = "啊齄丂狛狜" # Act with pytest.raises(HttpResponseError): @@ -771,17 +770,17 @@ def test_list_shares_enable_snapshot_virtual_directory_access(self, **kwargs): premium_storage_file_account_key = kwargs.pop("premium_storage_file_account_key") self._setup(premium_storage_file_account_name, premium_storage_file_account_key) - share = self._create_share(protocols="NFS", headers={'x-ms-enable-snapshot-virtual-directory-access': "False"}) + share = self._create_share(protocols="NFS", headers={"x-ms-enable-snapshot-virtual-directory-access": "False"}) # Act list_props = list(self.fsc.list_shares()) share_props = share.get_share_properties() # Assert - assert list_props[0].protocols[0] == 'NFS' + assert list_props[0].protocols[0] == "NFS" assert list_props[0].enable_snapshot_virtual_directory_access is False - assert share_props.protocols[0] == 'NFS' + assert share_props.protocols[0] == "NFS" assert share_props.enable_snapshot_virtual_directory_access is False self._delete_shares() @@ -818,16 +817,16 @@ def test_list_shares_leased_share(self, **kwargs): share = self._create_share("test1") # Act - lease = share.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = share.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") resp = list(self.fsc.list_shares()) # Assert assert resp is not None assert len(resp) >= 1 assert resp[0] is not None - assert resp[0].lease.duration == 'infinite' - assert resp[0].lease.status == 'locked' - assert resp[0].lease.state == 'leased' + assert resp[0].lease.duration == "infinite" + assert resp[0].lease.status == "locked" + assert resp[0].lease.state == "leased" lease.release() self._delete_shares() @@ -838,7 +837,7 @@ def test_list_shares_with_snapshot(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share = self._create_share('random2') + share = self._create_share("random2") snapshot1 = share.create_snapshot() snapshot2 = share.create_snapshot() @@ -849,8 +848,8 @@ def test_list_shares_with_snapshot(self, **kwargs): all_shares = list(shares) assert len(all_shares) == 3 self.assertNamedItemInContainer(all_shares, share.share_name) - self.assertNamedItemInContainer(all_shares, snapshot1['snapshot']) - self.assertNamedItemInContainer(all_shares, snapshot2['snapshot']) + self.assertNamedItemInContainer(all_shares, snapshot1["snapshot"]) + self.assertNamedItemInContainer(all_shares, snapshot2["snapshot"]) share.delete_share(delete_snapshots=True) self._delete_shares() @@ -861,7 +860,7 @@ def test_delete_snapshots_options(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share = self._create_share('prefix') + share = self._create_share("prefix") share.create_snapshot() share.create_snapshot() @@ -875,15 +874,15 @@ def test_delete_snapshots_options(self, **kwargs): share.delete_share(delete_snapshots=True) # Test "include" - share = self._create_share('prefix2') + share = self._create_share("prefix2") share.create_snapshot() - share.delete_share(delete_snapshots='include') + share.delete_share(delete_snapshots="include") # Test "include-leased" - share = self._create_share('prefix3') - lease = share.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share = self._create_share("prefix3") + lease = share.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") share.create_snapshot() - share.delete_share(delete_snapshots='include-leased', lease='00000000-1111-2222-3333-444444444444') + share.delete_share(delete_snapshots="include-leased", lease="00000000-1111-2222-3333-444444444444") @FileSharePreparer() @recorded_by_proxy @@ -892,8 +891,8 @@ def test_list_shares_with_prefix(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - self._create_share('othershare') - share = self._create_share('random2') + self._create_share("othershare") + share = self._create_share("random2") # Act shares = list(self.fsc.list_shares(name_starts_with=share.share_name)) @@ -912,7 +911,7 @@ def test_list_shares_with_include_metadata(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} share = self._get_share_reference() share.create_share(metadata=metadata) @@ -935,19 +934,20 @@ def test_list_shares_with_num_results_and_marker(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - prefix = 'listshare' + prefix = "listshare" share_names = [] for i in range(0, 4): share_names.append(self._create_share(prefix + str(i)).share_name) - #share_names.sort() + # share_names.sort() # Act generator1 = self.fsc.list_shares(prefix, results_per_page=2).by_page() shares1 = list(next(generator1)) - generator2 = self.fsc.list_shares( - prefix, results_per_page=2).by_page(continuation_token=generator1.continuation_token) + generator2 = self.fsc.list_shares(prefix, results_per_page=2).by_page( + continuation_token=generator1.continuation_token + ) shares2 = list(next(generator2)) # Assert @@ -1003,7 +1003,7 @@ def test_list_shares_account_sas_fails(self, **kwargs): storage_account_key.secret, ResourceTypes(service=True), AccountSasPermissions(list=True), - datetime.utcnow() - timedelta(hours=1) + datetime.utcnow() - timedelta(hours=1), ) # Act @@ -1023,7 +1023,7 @@ def test_set_share_metadata(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = self._create_share() - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act share.set_share_metadata(metadata) @@ -1040,7 +1040,7 @@ def test_get_share_metadata(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act client = self._get_share_reference() @@ -1059,7 +1059,7 @@ def test_get_share_metadata_with_snapshot(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act client = self._get_share_reference() @@ -1145,9 +1145,9 @@ def test_set_share_properties_with_root_squash(self, **kwargs): # # Assert assert share1_props.root_squash == ShareRootSquash.no_root_squash - assert share1_props.protocols == ['NFS'] + assert share1_props.protocols == ["NFS"] assert share2_props.root_squash == ShareRootSquash.root_squash - assert share2_props.protocols == ['NFS'] + assert share2_props.protocols == ["NFS"] @pytest.mark.playback_test_only @FileSharePreparer() @@ -1244,7 +1244,7 @@ def test_delete_share_with_non_existing_share(self, **kwargs): deleted = client.delete_share() log_as_str = log_captured.getvalue() - assert 'ERROR' not in log_as_str + assert "ERROR" not in log_as_str self._delete_shares() @FileSharePreparer() @@ -1292,7 +1292,7 @@ def test_set_share_acl(self, **kwargs): share.create_share() # Act - resp = share.set_share_access_policy(signed_identifiers={}) + resp = share.set_share_access_policy(signed_identifiers=dict()) # Assert acl = share.get_share_access_policy() @@ -1310,12 +1310,12 @@ def test_set_share_acl_with_empty_signed_identifiers(self, **kwargs): share.create_share() # Act - resp = share.set_share_access_policy({}) + resp = share.set_share_access_policy(dict()) # Assert acl = share.get_share_access_policy() assert acl is not None - assert len(acl.get('signed_identifiers')) == 0 + assert len(acl.get("signed_identifiers")) == 0 self._delete_shares() @FileSharePreparer() @@ -1323,7 +1323,7 @@ def test_set_share_acl_with_empty_signed_identifiers(self, **kwargs): def test_set_share_acl_with_signed_identifiers(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - variables = kwargs.pop('variables', {}) + variables = kwargs.pop("variables", {}) self._setup(storage_account_name, storage_account_key) share = self._get_share_reference() @@ -1331,9 +1331,9 @@ def test_set_share_acl_with_signed_identifiers(self, **kwargs): # Act identifiers = {} - expiry_time = self.get_datetime_variable(variables, 'expiry_time', datetime.utcnow() + timedelta(hours=1)) - start_time = self.get_datetime_variable(variables, 'start_time', datetime.utcnow() - timedelta(minutes=1)) - identifiers['testid'] = AccessPolicy( + expiry_time = self.get_datetime_variable(variables, "expiry_time", datetime.utcnow() + timedelta(hours=1)) + start_time = self.get_datetime_variable(variables, "start_time", datetime.utcnow() - timedelta(minutes=1)) + identifiers["testid"] = AccessPolicy( permission=ShareSasPermissions(write=True), expiry=expiry_time, start=start_time, @@ -1344,8 +1344,8 @@ def test_set_share_acl_with_signed_identifiers(self, **kwargs): # Assert acl = share.get_share_access_policy() assert acl is not None - assert len(acl['signed_identifiers']) == 1 - assert acl['signed_identifiers'][0].id == 'testid' + assert len(acl["signed_identifiers"]) == 1 + assert acl["signed_identifiers"][0].id == "testid" self._delete_shares() return variables @@ -1363,14 +1363,14 @@ def test_set_share_acl_too_many_ids(self, **kwargs): # Act identifiers = {} for i in range(0, 6): - identifiers['id{}'.format(i)] = AccessPolicy() + identifiers["id{}".format(i)] = AccessPolicy() # Assert with pytest.raises(ValueError) as e: share.set_share_access_policy(identifiers) - assert str(e.value.exception) == ( - 'Too many access policies provided. ' - 'The server does not support setting more than 5 access policies on a single resource.' + assert ( + str(e.value.exception) + == "Too many access policies provided. The server does not support setting more than 5 access policies on a single resource." ) self._delete_shares() @@ -1383,11 +1383,11 @@ def test_list_directories_and_files(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = self._create_share() dir0 = share.get_directory_client() - dir0.upload_file('file1', 'data1') - dir1 = share.get_directory_client('dir1') + dir0.upload_file("file1", "data1") + dir1 = share.get_directory_client("dir1") dir1.create_directory() - dir1.upload_file('file2', 'data2') - dir2 = share.get_directory_client('dir2') + dir1.upload_file("file2", "data2") + dir2 = share.get_directory_client("dir2") dir2.create_directory() # Act @@ -1397,9 +1397,9 @@ def test_list_directories_and_files(self, **kwargs): assert resp is not None assert len(resp) == 3 assert resp[0] is not None - self.assertNamedItemInContainer(resp, 'dir1') - self.assertNamedItemInContainer(resp, 'dir2') - self.assertNamedItemInContainer(resp, 'file1') + self.assertNamedItemInContainer(resp, "dir1") + self.assertNamedItemInContainer(resp, "dir2") + self.assertNamedItemInContainer(resp, "file1") self._delete_shares() @FileSharePreparer() @@ -1410,16 +1410,15 @@ def test_list_directories_and_files_with_snapshot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_name = self._create_share() - dir1 = share_name.get_directory_client('dir1') + dir1 = share_name.get_directory_client("dir1") dir1.create_directory() - dir2 = share_name.get_directory_client('dir2') + dir2 = share_name.get_directory_client("dir2") dir2.create_directory() snapshot1 = share_name.create_snapshot() - dir3 = share_name.get_directory_client('dir3') + dir3 = share_name.get_directory_client("dir3") dir3.create_directory() - file1 = share_name.get_file_client('file1') - file1.upload_file('data') - + file1 = share_name.get_file_client("file1") + file1.upload_file("data") # Act snapshot_client = self.fsc.get_share_client(share_name.share_name, snapshot=snapshot1) @@ -1429,8 +1428,8 @@ def test_list_directories_and_files_with_snapshot(self, **kwargs): assert resp is not None assert len(resp) == 2 assert resp[0] is not None - self.assertNamedItemInContainer(resp, 'dir1') - self.assertNamedItemInContainer(resp, 'dir2') + self.assertNamedItemInContainer(resp, "dir1") + self.assertNamedItemInContainer(resp, "dir2") self._delete_shares() @FileSharePreparer() @@ -1441,12 +1440,12 @@ def test_list_directories_and_files_with_num_results(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_name = self._create_share() - dir1 = share_name.create_directory('dir1') + dir1 = share_name.create_directory("dir1") root = share_name.get_directory_client() - root.upload_file('filea1', '1024') - root.upload_file('filea2', '1024') - root.upload_file('filea3', '1024') - root.upload_file('fileb1', '1024') + root.upload_file("filea1", "1024") + root.upload_file("filea2", "1024") + root.upload_file("filea3", "1024") + root.upload_file("fileb1", "1024") # Act result = share_name.list_directories_and_files(results_per_page=2).by_page() @@ -1455,8 +1454,8 @@ def test_list_directories_and_files_with_num_results(self, **kwargs): # Assert assert result is not None assert len(result) == 2 - self.assertNamedItemInContainer(result, 'dir1') - self.assertNamedItemInContainer(result, 'filea1') + self.assertNamedItemInContainer(result, "dir1") + self.assertNamedItemInContainer(result, "filea1") self._delete_shares() @FileSharePreparer() @@ -1467,29 +1466,29 @@ def test_list_directories_and_files_with_num_results_and_marker(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_name = self._create_share() - dir1 = share_name.get_directory_client('dir1') + dir1 = share_name.get_directory_client("dir1") dir1.create_directory() - dir1.upload_file('filea1', '1024') - dir1.upload_file('filea2', '1024') - dir1.upload_file('filea3', '1024') - dir1.upload_file('fileb1', '1024') + dir1.upload_file("filea1", "1024") + dir1.upload_file("filea2", "1024") + dir1.upload_file("filea3", "1024") + dir1.upload_file("fileb1", "1024") # Act - generator1 = share_name.list_directories_and_files( - 'dir1', results_per_page=2).by_page() + generator1 = share_name.list_directories_and_files("dir1", results_per_page=2).by_page() result1 = list(next(generator1)) - generator2 = share_name.list_directories_and_files( - 'dir1', results_per_page=2).by_page(continuation_token=generator1.continuation_token) + generator2 = share_name.list_directories_and_files("dir1", results_per_page=2).by_page( + continuation_token=generator1.continuation_token + ) result2 = list(next(generator2)) # Assert assert len(result1) == 2 assert len(result2) == 2 - self.assertNamedItemInContainer(result1, 'filea1') - self.assertNamedItemInContainer(result1, 'filea2') - self.assertNamedItemInContainer(result2, 'filea3') - self.assertNamedItemInContainer(result2, 'fileb1') + self.assertNamedItemInContainer(result1, "filea1") + self.assertNamedItemInContainer(result1, "filea2") + self.assertNamedItemInContainer(result2, "filea3") + self.assertNamedItemInContainer(result2, "fileb1") assert generator2.continuation_token == None self._delete_shares() @@ -1501,24 +1500,24 @@ def test_list_directories_and_files_with_prefix(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = self._create_share() - dir1 = share.create_directory('dir1') - share.create_directory('dir1/pref_dir3') - share.create_directory('dir2') + dir1 = share.create_directory("dir1") + share.create_directory("dir1/pref_dir3") + share.create_directory("dir2") root = share.get_directory_client() - root.upload_file('file1', '1024') - dir1.upload_file('pref_file2', '1025') - dir1.upload_file('file3', '1025') + root.upload_file("file1", "1024") + dir1.upload_file("pref_file2", "1025") + dir1.upload_file("file3", "1025") # Act - resp = list(share.list_directories_and_files('dir1', name_starts_with='pref')) + resp = list(share.list_directories_and_files("dir1", name_starts_with="pref")) # Assert assert resp is not None assert len(resp) == 2 assert resp[0] is not None - self.assertNamedItemInContainer(resp, 'pref_file2') - self.assertNamedItemInContainer(resp, 'pref_dir3') + self.assertNamedItemInContainer(resp, "pref_file2") + self.assertNamedItemInContainer(resp, "pref_dir3") self._delete_shares() @pytest.mark.live_test_only @@ -1528,9 +1527,9 @@ def test_shared_access_share(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_name = 'file1' - dir_name = 'dir1' - data = b'hello world' + file_name = "file1" + dir_name = "dir1" + data = b"hello world" share = self._create_share() dir1 = share.create_directory(dir_name) @@ -1547,13 +1546,13 @@ def test_shared_access_share(self, **kwargs): sas_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=share.share_name, - file_path=dir_name + '/' + file_name, + file_path=dir_name + "/" + file_name, credential=token, ) # Act print(sas_client.url) - response = requests.get(sas_client.url, timeout=15) + response = requests.get(sas_client.url) # Assert assert response.ok @@ -1567,9 +1566,11 @@ def test_create_permission_for_share(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - user_given_permission = "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" \ - "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" \ - "S-1-5-21-397955417-626881126-188441444-3053964)" + user_given_permission = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)" + ) share_client = self._create_share() permission_key = share_client.create_permission_for_share(user_given_permission) assert permission_key is not None @@ -1590,25 +1591,27 @@ def test_get_permission_format(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = self._create_share() - user_given_permission_sddl = ("O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" - "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" - "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL") - user_given_permission_binary = ("AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" - "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" - "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=") + user_given_permission_sddl = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL" + ) + user_given_permission_binary = ( + "AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" + "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" + "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=" + ) permission_key = share_client.create_permission_for_share(user_given_permission_sddl) assert permission_key is not None server_returned_permission = share_client.get_permission_for_share( - permission_key, - file_permission_format="sddl" + permission_key, file_permission_format="sddl" ) assert server_returned_permission == user_given_permission_sddl server_returned_permission = share_client.get_permission_for_share( - permission_key, - file_permission_format="binary" + permission_key, file_permission_format="binary" ) assert server_returned_permission == user_given_permission_binary @@ -1642,15 +1645,15 @@ def test_delete_directory_from_share(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = self._create_share() - dir1 = share.create_directory('dir1') - share.create_directory('dir2') - share.create_directory('dir3') + dir1 = share.create_directory("dir1") + share.create_directory("dir2") + share.create_directory("dir3") # Act resp = list(share.list_directories_and_files()) assert len(resp) == 3 - share.delete_directory('dir3') + share.delete_directory("dir3") # Assert resp = list(share.list_directories_and_files()) @@ -1672,11 +1675,7 @@ def test_share_paid_bursting(self, **kwargs): # Act / Assert share = self._get_share_reference() - share.create_share( - paid_bursting_enabled=True, - paid_bursting_bandwidth_mibps=5000, - paid_bursting_iops=1000 - ) + share.create_share(paid_bursting_enabled=True, paid_bursting_bandwidth_mibps=5000, paid_bursting_iops=1000) share_props = share.get_share_properties() assert share_props.paid_bursting_enabled assert share_props.paid_bursting_bandwidth_mibps == 5000 @@ -1686,7 +1685,7 @@ def test_share_paid_bursting(self, **kwargs): root_squash="NoRootSquash", paid_bursting_enabled=True, paid_bursting_bandwidth_mibps=mibps, - paid_bursting_iops=iops + paid_bursting_iops=iops, ) share_props = share.get_share_properties() share_name = share_props.name @@ -1721,8 +1720,8 @@ def test_share_client_with_oauth(self, **kwargs): token_credential = self.get_credential(ShareClient) self._setup(storage_account_name, storage_account_key) - first_share = self._create_share('test1') - second_share = self._create_share('test2') + first_share = self._create_share("test1") + second_share = self._create_share("test2") share_names = {share.name for share in self.fsc.list_shares()} assert first_share.share_name in share_names @@ -1732,29 +1731,29 @@ def test_share_client_with_oauth(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=first_share.share_name, credential=token_credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) second_share_client = ShareClient( self.account_url(storage_account_name, "file"), share_name=second_share.share_name, credential=token_credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) first_share_props = first_share_client.get_share_properties() second_share_props = second_share_client.get_share_properties() assert first_share_props is not None assert first_share_props.name == first_share.share_name - assert first_share_props.access_tier == 'TransactionOptimized' + assert first_share_props.access_tier == "TransactionOptimized" assert second_share_props is not None assert second_share_props.name == second_share.share_name - assert second_share_props.access_tier == 'TransactionOptimized' + assert second_share_props.access_tier == "TransactionOptimized" - first_share_client.set_share_properties(access_tier='Hot') + first_share_client.set_share_properties(access_tier="Hot") first_share_props = first_share_client.get_share_properties() assert first_share_props is not None assert first_share_props.name == first_share.share_name - assert first_share_props.access_tier == 'Hot' + assert first_share_props.access_tier == "Hot" share_names = {share.name for share in self.fsc.list_shares()} assert first_share.share_name in share_names @@ -1772,25 +1771,22 @@ def test_share_lease_with_oauth(self, **kwargs): # Arrange self._setup(storage_account_name, storage_account_key) - share = self._create_share('test') + share = self._create_share("test") share_client = ShareClient( self.account_url(storage_account_name, "file"), share_name=share.share_name, credential=token_credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) # Act / Assert lease_duration = 60 - lease_id = '00000000-1111-2222-3333-444444444444' - lease = share_client.acquire_lease( - lease_id=lease_id, - lease_duration=lease_duration - ) + lease_id = "00000000-1111-2222-3333-444444444444" + lease = share_client.acquire_lease(lease_id=lease_id, lease_duration=lease_duration) props = share_client.get_share_properties(lease=lease) - assert props.lease.duration == 'fixed' - assert props.lease.state == 'leased' - assert props.lease.status == 'locked' + assert props.lease.duration == "fixed" + assert props.lease.state == "leased" + assert props.lease.status == "locked" lease.renew() assert lease.id == lease_id @@ -1808,9 +1804,9 @@ def test_create_share_access_tier_premium(self, **kwargs): self._setup(premium_storage_file_account_name, premium_storage_file_account_key) share = self._get_share_reference() - share.create_share(access_tier='Premium') + share.create_share(access_tier="Premium") props = share.get_share_properties() - assert props.access_tier == 'Premium' + assert props.access_tier == "Premium" finally: self._delete_shares() @@ -1825,9 +1821,9 @@ def test_set_share_properties_access_tier_premium(self, **kwargs): share = self._get_share_reference() share.create_share() - share.set_share_properties(access_tier='Premium') + share.set_share_properties(access_tier="Premium") props = share.get_share_properties() - assert props.access_tier == 'Premium' + assert props.access_tier == "Premium" finally: self._delete_shares() @@ -1855,11 +1851,7 @@ def test_provisioned_billing_v2(self, **kwargs): assert props.next_provisioned_iops_downgrade is not None assert props.next_provisioned_bandwidth_downgrade is not None - share.set_share_properties( - access_tier="Hot", - provisioned_iops=3000, - provisioned_bandwidth_mibps=125 - ) + share.set_share_properties(access_tier="Hot", provisioned_iops=3000, provisioned_bandwidth_mibps=125) shares = list(self.fsc.list_shares()) @@ -1883,12 +1875,10 @@ def test_get_user_delegation_sas(self, **kwargs): token_credential = self.get_credential(ShareServiceClient) service = ShareServiceClient( - self.account_url(storage_account_name, "file"), - credential=token_credential, - token_intent="backup" + self.account_url(storage_account_name, "file"), credential=token_credential, token_intent="backup" ) - start = self.get_datetime_variable(variables, 'start_time', datetime.utcnow()) - expiry = self.get_datetime_variable(variables, 'expiry_time', datetime.utcnow() + timedelta(hours=1)) + start = self.get_datetime_variable(variables, "start_time", datetime.utcnow()) + expiry = self.get_datetime_variable(variables, "expiry_time", datetime.utcnow() + timedelta(hours=1)) user_delegation_key_1 = service.get_user_delegation_key(start=start, expiry=expiry) user_delegation_key_2 = service.get_user_delegation_key(start=start, expiry=expiry) @@ -1914,27 +1904,23 @@ def test_get_user_delegation_sas(self, **kwargs): @pytest.mark.live_test_only @FileSharePreparer() - def test_share_cross_tenant_sas(self, **kwargs): # pylint: disable=too-many-locals + def test_share_cross_tenant_sas(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) token_credential = self.get_credential(ShareServiceClient) service = ShareServiceClient( - self.account_url(storage_account_name, "file"), - credential=token_credential, - token_intent="backup" + self.account_url(storage_account_name, "file"), credential=token_credential, token_intent="backup" ) start = datetime.utcnow() expiry = datetime.utcnow() + timedelta(hours=1) token = token_credential.get_token("https://storage.azure.com/.default") - decoded = jwt.decode(token.token, options={"verify_signature": False}) # pylint: disable=no-member + decoded = jwt.decode(token.token, options={"verify_signature": False}) user_delegation_oid = decoded.get("oid") delegated_user_tid = decoded.get("tid") user_delegation_key = service.get_user_delegation_key( - start=start, - expiry=expiry, - delegated_user_tid=delegated_user_tid + start=start, expiry=expiry, delegated_user_tid=delegated_user_tid ) assert user_delegation_key is not None @@ -1956,16 +1942,14 @@ def test_share_cross_tenant_sas(self, **kwargs): # pylint: disable=too-many-loc permission=ShareSasPermissions(read=True, list=True), expiry=datetime.utcnow() + timedelta(hours=1), user_delegation_key=user_delegation_key, - user_delegation_oid=user_delegation_oid + user_delegation_oid=user_delegation_oid, ) assert "sduoid=" + user_delegation_oid in share_token assert "skdutid=" + delegated_user_tid in share_token share_client = ShareClient.from_share_url( - f"{share.url}?{share_token}", - credential=token_credential, - token_intent="backup" + f"{share.url}?{share_token}", credential=token_credential, token_intent="backup" ) structure = list(share_client.list_directories_and_files()) assert structure is not None @@ -1979,20 +1963,19 @@ def test_share_cross_tenant_sas(self, **kwargs): # pylint: disable=too-many-loc permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), user_delegation_key=user_delegation_key, - user_delegation_oid=user_delegation_oid + user_delegation_oid=user_delegation_oid, ) assert "sduoid=" + user_delegation_oid in file_token assert "skdutid=" + delegated_user_tid in file_token file_client = ShareFileClient.from_file_url( - f"{file.url}?{file_token}", - credential=token_credential, - token_intent="backup" + f"{file.url}?{file_token}", credential=token_credential, token_intent="backup" ) content = file_client.download_file().readall() assert content == data + # ------------------------------------------------------------------------------ -if __name__ == '__main__': +if __name__ == "__main__": unittest.main() diff --git a/sdk/storage/azure-storage-file-share/tests/test_share_async.py b/sdk/storage/azure-storage-file-share/tests/test_share_async.py index 1c109bedc581..a12f3a836e98 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_share_async.py +++ b/sdk/storage/azure-storage-file-share/tests/test_share_async.py @@ -1,29 +1,23 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- - +import jwt import os import time from datetime import datetime, timedelta -import jwt import pytest import requests - -from devtools_testutils.aio import recorded_by_proxy_async -from devtools_testutils.storage import LogCaptured -from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase -from settings.testcase import FileSharePreparer - from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ) -from azure.core.pipeline.transport import AioHttpTransport # pylint: disable=no-name-in-module +from azure.core.pipeline.transport import AioHttpTransport from azure.storage.fileshare import ( AccessPolicy, AccountSasPermissions, @@ -36,13 +30,18 @@ ShareProtocols, ShareRootSquash, ShareSasPermissions, + ShareServiceClient, StorageErrorCode, ) from azure.storage.fileshare.aio import ShareClient, ShareFileClient, ShareServiceClient +from devtools_testutils.aio import recorded_by_proxy_async +from devtools_testutils.storage import LogCaptured +from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase +from settings.testcase import FileSharePreparer # ------------------------------------------------------------------------------ -TEST_SHARE_PREFIX = 'share' +TEST_SHARE_PREFIX = "share" TEST_INTENT = "backup" # ------------------------------------------------------------------------------ @@ -63,11 +62,10 @@ def _teardown(self, FILE_PATH): async def _delete_shares(self, prefix=TEST_SHARE_PREFIX): async for l in self.fsc.list_shares(include_snapshots=True): - if l.name.startswith(prefix): - try: - await self.fsc.delete_share(l.name, delete_snapshots=True) - except: - pass + try: + await self.fsc.delete_share(l.name, delete_snapshots=True) + except: + pass # --Helpers----------------------------------------------------------------- def _get_share_reference(self, prefix=TEST_SHARE_PREFIX): @@ -117,7 +115,7 @@ async def test_create_share_with_oauth_fails(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=share_name, credential=token_credential, - file_request_intent=TEST_INTENT + file_request_intent=TEST_INTENT, ) @FileSharePreparer() @@ -135,12 +133,11 @@ async def test_create_share_snapshot(self, **kwargs): # Assert assert created - assert snapshot['snapshot'] is not None - assert snapshot['etag'] is not None - assert snapshot['last_modified'] is not None + assert snapshot["snapshot"] is not None + assert snapshot["etag"] is not None + assert snapshot["last_modified"] is not None await self._delete_shares(share.share_name) - @FileSharePreparer() @recorded_by_proxy_async async def test_create_snapshot_with_metadata(self, **kwargs): @@ -161,14 +158,14 @@ async def test_create_snapshot_with_metadata(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=share.share_name, snapshot=snapshot, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) snapshot_props = await snapshot_client.get_share_properties() # Assert assert created - assert snapshot['snapshot'] is not None - assert snapshot['etag'] is not None - assert snapshot['last_modified'] is not None + assert snapshot["snapshot"] is not None + assert snapshot["etag"] is not None + assert snapshot["last_modified"] is not None assert share_props.metadata == metadata assert snapshot_props.metadata == metadata2 await self._delete_shares(share.share_name) @@ -214,9 +211,9 @@ async def test_lease_share_acquire_and_release(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') + share_client = await self._create_share("test") # Act - lease = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") await lease.release() # Assert @@ -237,11 +234,11 @@ async def test_acquire_lease_on_sharesnapshot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=share.share_name, snapshot=snapshot, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) - share_lease = await share.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') - share_snapshot_lease = await snapshot_client.acquire_lease(lease_id='44444444-3333-2222-1111-000000000000') + share_lease = await share.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") + share_snapshot_lease = await snapshot_client.acquire_lease(lease_id="44444444-3333-2222-1111-000000000000") # Assert with pytest.raises(HttpResponseError): @@ -250,9 +247,9 @@ async def test_acquire_lease_on_sharesnapshot(self, **kwargs): with pytest.raises(HttpResponseError): await snapshot_client.get_share_properties(lease=share_lease) - assert snapshot['snapshot'] is not None - assert snapshot['etag'] is not None - assert snapshot['last_modified'] is not None + assert snapshot["snapshot"] is not None + assert snapshot["etag"] is not None + assert snapshot["last_modified"] is not None assert share_lease is not None assert share_snapshot_lease is not None assert share_lease != share_snapshot_lease @@ -268,8 +265,8 @@ async def test_lease_share_renew(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') - lease = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + share_client = await self._create_share("test") + lease = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) self.sleep(10) lease_id_start = lease.id @@ -291,16 +288,16 @@ async def test_lease_share_with_duration(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') + share_client = await self._create_share("test") # Act - lease = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + lease = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) # Assert with pytest.raises(HttpResponseError): - await share_client.acquire_lease(lease_id='44444444-3333-2222-1111-000000000000') + await share_client.acquire_lease(lease_id="44444444-3333-2222-1111-000000000000") self.sleep(17) - await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") @FileSharePreparer() @recorded_by_proxy_async @@ -309,10 +306,10 @@ async def test_lease_share_twice(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') + share_client = await self._create_share("test") # Act - lease = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + lease = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) # Assert lease2 = await share_client.acquire_lease(lease_id=lease.id) @@ -325,10 +322,10 @@ async def test_lease_share_with_proposed_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') + share_client = await self._create_share("test") # Act - proposed_lease_id = '55e97f64-73e8-4390-838d-d9e84a374321' + proposed_lease_id = "55e97f64-73e8-4390-838d-d9e84a374321" lease = await share_client.acquire_lease(lease_id=proposed_lease_id) # Assert @@ -341,11 +338,11 @@ async def test_lease_share_change_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') + share_client = await self._create_share("test") # Act - lease_id = '29e0b239-ecda-4f69-bfa3-95f6af91464c' - lease = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease_id = "29e0b239-ecda-4f69-bfa3-95f6af91464c" + lease = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") lease_id1 = lease.id await lease.change(proposed_lease_id=lease_id) await lease.renew() @@ -364,9 +361,9 @@ async def test_set_share_metadata_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test1') - metadata = {'hello': 'world', 'number': '43'} - lease_id = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share_client = await self._create_share("test1") + metadata = {"hello": "world", "number": "43"} + lease_id = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act await share_client.set_share_metadata(metadata, lease=lease_id) @@ -383,10 +380,10 @@ async def test_get_share_metadata_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') - metadata = {'hello': 'world', 'number': '43'} + share_client = await self._create_share("test") + metadata = {"hello": "world", "number": "43"} await share_client.set_share_metadata(metadata) - lease_id = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease_id = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act props = await share_client.get_share_properties(lease=lease_id) @@ -402,10 +399,10 @@ async def test_get_share_properties_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') - metadata = {'hello': 'world', 'number': '43'} + share_client = await self._create_share("test") + metadata = {"hello": "world", "number": "43"} await share_client.set_share_metadata(metadata) - lease_id = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease_id = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act props = await share_client.get_share_properties(lease=lease_id) @@ -414,9 +411,9 @@ async def test_get_share_properties_with_lease_id(self, **kwargs): # Assert assert props is not None assert props.metadata == metadata - assert props.lease.duration == 'infinite' - assert props.lease.state == 'leased' - assert props.lease.status == 'locked' + assert props.lease.duration == "infinite" + assert props.lease.state == "leased" + assert props.lease.status == "locked" @FileSharePreparer() @recorded_by_proxy_async @@ -425,41 +422,39 @@ async def test_get_share_acl_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') - lease_id = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share_client = await self._create_share("test") + lease_id = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act acl = await share_client.get_share_access_policy(lease=lease_id) # Assert assert acl is not None - assert acl.get('public_access') is None + assert acl.get("public_access") is None @FileSharePreparer() @recorded_by_proxy_async async def test_set_share_acl_with_lease_id(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - variables = kwargs.pop('variables', {}) + variables = kwargs.pop("variables", {}) self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') - lease_id = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share_client = await self._create_share("test") + lease_id = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") # Act - expiry_time = self.get_datetime_variable(variables, 'expiry_time', datetime.utcnow() + timedelta(hours=1)) - start_time = self.get_datetime_variable(variables, 'start_time', datetime.utcnow()) - access_policy = AccessPolicy(permission=ShareSasPermissions(read=True), - expiry=expiry_time, - start=start_time) - signed_identifiers = {'testid': access_policy} + expiry_time = self.get_datetime_variable(variables, "expiry_time", datetime.utcnow() + timedelta(hours=1)) + start_time = self.get_datetime_variable(variables, "start_time", datetime.utcnow()) + access_policy = AccessPolicy(permission=ShareSasPermissions(read=True), expiry=expiry_time, start=start_time) + signed_identifiers = {"testid": access_policy} await share_client.set_share_access_policy(signed_identifiers, lease=lease_id) # Assert acl = await share_client.get_share_access_policy() assert acl is not None - assert acl.get('public_access') is None + assert acl.get("public_access") is None return variables @@ -470,10 +465,10 @@ async def test_lease_share_break_period(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') + share_client = await self._create_share("test") # Act - lease = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + lease = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) # Assert await lease.break_lease(lease_break_period=5) @@ -488,8 +483,8 @@ async def test_delete_share_with_lease_id(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_client = await self._create_share('test') - lease = await share_client.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444', lease_duration=15) + share_client = await self._create_share("test") + lease = await share_client.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444", lease_duration=15) # Assert with pytest.raises(HttpResponseError): @@ -555,7 +550,7 @@ async def test_delete_snapshot(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=share.share_name, snapshot=snapshot, - credential=storage_account_key.secret + credential=storage_account_key.secret, ) deleted = await snapshot_client.delete_share() @@ -603,7 +598,7 @@ async def test_create_share_with_metadata(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act client = self._get_share_reference() @@ -709,7 +704,7 @@ async def test_share_snapshot_not_exists(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = await self._create_share() - made_up_snapshot = '2017-07-19T06:53:46.0000000Z' + made_up_snapshot = "2017-07-19T06:53:46.0000000Z" # Act snapshot_client = self.fsc.get_share_client(share.share_name, snapshot=made_up_snapshot) @@ -726,7 +721,7 @@ async def test_unicode_create_share_unicode_name(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share_name = '啊齄丂狛狜' + share_name = "啊齄丂狛狜" # Act with pytest.raises(HttpResponseError): @@ -765,10 +760,7 @@ async def test_list_shares_enable_snapshot_virtual_directory_access(self, **kwar self._setup(premium_storage_file_account_name, premium_storage_file_account_key) share = await self._create_share( - protocols="NFS", - headers={ - 'x-ms-enable-snapshot-virtual-directory-access': "False" - } + protocols="NFS", headers={"x-ms-enable-snapshot-virtual-directory-access": "False"} ) # Act @@ -778,10 +770,10 @@ async def test_list_shares_enable_snapshot_virtual_directory_access(self, **kwar share_props = await share.get_share_properties() # Assert - assert list_props[0].protocols[0] == 'NFS' + assert list_props[0].protocols[0] == "NFS" assert list_props[0].enable_snapshot_virtual_directory_access is False - assert share_props.protocols[0] == 'NFS' + assert share_props.protocols[0] == "NFS" assert share_props.enable_snapshot_virtual_directory_access is False await self._delete_shares() @@ -820,7 +812,7 @@ async def test_list_shares_leased_share(self, **kwargs): share = await self._create_share() # Act - lease = await share.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + lease = await share.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") resp = [] async for s in self.fsc.list_shares(): resp.append(s) @@ -829,9 +821,9 @@ async def test_list_shares_leased_share(self, **kwargs): assert resp is not None assert len(resp) >= 1 assert resp[0] is not None - assert resp[0].lease.duration == 'infinite' - assert resp[0].lease.status == 'locked' - assert resp[0].lease.state == 'leased' + assert resp[0].lease.duration == "infinite" + assert resp[0].lease.status == "locked" + assert resp[0].lease.state == "leased" await lease.release() await self._delete_shares() @@ -842,7 +834,7 @@ async def test_list_shares_with_snapshot(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share = await self._create_share('random3') + share = await self._create_share("random3") snapshot1 = await share.create_snapshot() snapshot2 = await share.create_snapshot() @@ -856,8 +848,8 @@ async def test_list_shares_with_snapshot(self, **kwargs): all_shares.append(s) assert len(all_shares) == 3 self.assertNamedItemInContainer(all_shares, share.share_name) - self.assertNamedItemInContainer(all_shares, snapshot1['snapshot']) - self.assertNamedItemInContainer(all_shares, snapshot2['snapshot']) + self.assertNamedItemInContainer(all_shares, snapshot1["snapshot"]) + self.assertNamedItemInContainer(all_shares, snapshot2["snapshot"]) await self._delete_shares(share.share_name) @FileSharePreparer() @@ -867,7 +859,7 @@ async def test_delete_snapshots_options(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share = await self._create_share('prefix') + share = await self._create_share("prefix") await share.create_snapshot() await share.create_snapshot() @@ -881,15 +873,15 @@ async def test_delete_snapshots_options(self, **kwargs): await share.delete_share(delete_snapshots=True) # Test "include" - share = await self._create_share('prefix2') + share = await self._create_share("prefix2") await share.create_snapshot() - await share.delete_share(delete_snapshots='include') + await share.delete_share(delete_snapshots="include") # Test "include-leased" - share = await self._create_share('prefix3') - lease = await share.acquire_lease(lease_id='00000000-1111-2222-3333-444444444444') + share = await self._create_share("prefix3") + lease = await share.acquire_lease(lease_id="00000000-1111-2222-3333-444444444444") await share.create_snapshot() - await share.delete_share(delete_snapshots='include-leased', lease='00000000-1111-2222-3333-444444444444') + await share.delete_share(delete_snapshots="include-leased", lease="00000000-1111-2222-3333-444444444444") @FileSharePreparer() @recorded_by_proxy_async @@ -898,8 +890,8 @@ async def test_list_shares_with_prefix(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - await self._create_share('othershare') - share = await self._create_share('random4') + await self._create_share("othershare") + share = await self._create_share("random4") # Act shares = [] @@ -920,7 +912,7 @@ async def test_list_shares_with_include_metadata(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} share = self._get_share_reference() await share.create_share(metadata=metadata) @@ -945,7 +937,7 @@ async def test_list_shares_with_num_results_and_marker(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - prefix = 'listshare' + prefix = "listshare" share_names = [] for i in range(0, 4): share = await self._create_share(prefix + str(i)) @@ -958,8 +950,9 @@ async def test_list_shares_with_num_results_and_marker(self, **kwargs): shares1 = [] async for s in await generator1.__anext__(): shares1.append(s) - generator2 = self.fsc.list_shares( - prefix, results_per_page=2).by_page(continuation_token=generator1.continuation_token) + generator2 = self.fsc.list_shares(prefix, results_per_page=2).by_page( + continuation_token=generator1.continuation_token + ) shares2 = [] async for s in await generator2.__anext__(): shares2.append(s) @@ -1019,7 +1012,7 @@ async def test_list_shares_account_sas_fails(self, **kwargs): storage_account_key.secret, ResourceTypes(service=True), AccountSasPermissions(list=True), - datetime.utcnow() - timedelta(hours=1) + datetime.utcnow() - timedelta(hours=1), ) # Act @@ -1033,7 +1026,6 @@ async def test_list_shares_account_sas_fails(self, **kwargs): assert e.value.error_code == StorageErrorCode.AUTHENTICATION_FAILED assert "authenticationerrordetail" in e.value.message - @FileSharePreparer() @recorded_by_proxy_async async def test_set_share_metadata(self, **kwargs): @@ -1042,7 +1034,7 @@ async def test_set_share_metadata(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = await self._create_share() - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act await share.set_share_metadata(metadata) @@ -1060,7 +1052,7 @@ async def test_get_share_metadata(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act client = self._get_share_reference() @@ -1079,7 +1071,7 @@ async def test_get_share_metadata_with_snapshot(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - metadata = {'hello': 'world', 'number': '42'} + metadata = {"hello": "world", "number": "42"} # Act client = self._get_share_reference() @@ -1269,7 +1261,7 @@ async def test_delete_share_with_non_existing_share(self, **kwargs): deleted = await client.delete_share() log_as_str = log_captured.getvalue() - assert 'ERROR' not in log_as_str + assert "ERROR" not in log_as_str await self._delete_shares(client.share_name) @FileSharePreparer() @@ -1317,7 +1309,7 @@ async def test_set_share_acl(self, **kwargs): await share.create_share() # Act - resp = await share.set_share_access_policy(signed_identifiers={}) + resp = await share.set_share_access_policy(signed_identifiers=dict()) # Assert acl = await share.get_share_access_policy() @@ -1335,12 +1327,12 @@ async def test_set_share_acl_with_empty_signed_identifiers(self, **kwargs): await share.create_share() # Act - resp = await share.set_share_access_policy({}) + resp = await share.set_share_access_policy(dict()) # Assert acl = await share.get_share_access_policy() assert acl is not None - assert len(acl.get('signed_identifiers')) == 0 + assert len(acl.get("signed_identifiers")) == 0 await self._delete_shares(share.share_name) @FileSharePreparer() @@ -1348,7 +1340,7 @@ async def test_set_share_acl_with_empty_signed_identifiers(self, **kwargs): async def test_set_share_acl_with_signed_identifiers(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") - variables = kwargs.pop('variables', {}) + variables = kwargs.pop("variables", {}) self._setup(storage_account_name, storage_account_key) share = self._get_share_reference() @@ -1356,9 +1348,9 @@ async def test_set_share_acl_with_signed_identifiers(self, **kwargs): # Act identifiers = {} - expiry_time = self.get_datetime_variable(variables, 'expiry_time', datetime.utcnow() + timedelta(hours=1)) - start_time = self.get_datetime_variable(variables, 'start_time', datetime.utcnow() - timedelta(minutes=1)) - identifiers['testid'] = AccessPolicy( + expiry_time = self.get_datetime_variable(variables, "expiry_time", datetime.utcnow() + timedelta(hours=1)) + start_time = self.get_datetime_variable(variables, "start_time", datetime.utcnow() - timedelta(minutes=1)) + identifiers["testid"] = AccessPolicy( permission=ShareSasPermissions(write=True), expiry=expiry_time, start=start_time, @@ -1369,8 +1361,8 @@ async def test_set_share_acl_with_signed_identifiers(self, **kwargs): # Assert acl = await share.get_share_access_policy() assert acl is not None - assert len(acl['signed_identifiers']) == 1 - assert acl['signed_identifiers'][0].id == 'testid' + assert len(acl["signed_identifiers"]) == 1 + assert acl["signed_identifiers"][0].id == "testid" await self._delete_shares(share.share_name) return variables @@ -1388,13 +1380,15 @@ async def test_set_share_acl_too_many_ids(self, **kwargs): # Act identifiers = {} for i in range(0, 6): - identifiers['id{}'.format(i)] = AccessPolicy() + identifiers["id{}".format(i)] = AccessPolicy() # Assert with pytest.raises(ValueError) as e: await share.set_share_access_policy(identifiers) - assert str(e.value.args[0]) == ('Too many access policies provided. The server does not ' - 'support setting more than 5 access policies on a single resource.') + assert ( + str(e.value.args[0]) + == "Too many access policies provided. The server does not support setting more than 5 access policies on a single resource." + ) await self._delete_shares(share.share_name) @FileSharePreparer() @@ -1406,11 +1400,11 @@ async def test_list_directories_and_files(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = await self._create_share() dir0 = share.get_directory_client() - await dir0.upload_file('file1', 'data1') - dir1 = share.get_directory_client('dir1') + await dir0.upload_file("file1", "data1") + dir1 = share.get_directory_client("dir1") await dir1.create_directory() - await dir1.upload_file('file2', 'data2') - dir2 = share.get_directory_client('dir2') + await dir1.upload_file("file2", "data2") + dir2 = share.get_directory_client("dir2") await dir2.create_directory() # Act @@ -1422,10 +1416,10 @@ async def test_list_directories_and_files(self, **kwargs): assert resp is not None assert len(resp) == 3 assert resp[0] is not None - self.assertNamedItemInContainer(resp, 'dir1') - self.assertNamedItemInContainer(resp, 'dir2') - self.assertNamedItemInContainer(resp, 'file1') - await self._delete_shares(share.share_name) + self.assertNamedItemInContainer(resp, "dir1") + self.assertNamedItemInContainer(resp, "dir2") + self.assertNamedItemInContainer(resp, "file1") + await self._delete_shares(share) @FileSharePreparer() @recorded_by_proxy_async @@ -1434,19 +1428,19 @@ async def test_list_directories_and_files_with_snapshot(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share = await self._create_share() - dir1 = share.get_directory_client('dir1') + share_name = await self._create_share() + dir1 = share_name.get_directory_client("dir1") await dir1.create_directory() - dir2 = share.get_directory_client('dir2') + dir2 = share_name.get_directory_client("dir2") await dir2.create_directory() - snapshot1 = await share.create_snapshot() - dir3 = share.get_directory_client('dir3') + snapshot1 = await share_name.create_snapshot() + dir3 = share_name.get_directory_client("dir3") await dir3.create_directory() - file1 = share.get_file_client('file1') - await file1.upload_file('data') + file1 = share_name.get_file_client("file1") + await file1.upload_file("data") # Act - snapshot_client = self.fsc.get_share_client(share.share_name, snapshot=snapshot1) + snapshot_client = self.fsc.get_share_client(share_name.share_name, snapshot=snapshot1) resp = [] async for d in snapshot_client.list_directories_and_files(): resp.append(d) @@ -1455,9 +1449,9 @@ async def test_list_directories_and_files_with_snapshot(self, **kwargs): assert resp is not None assert len(resp) == 2 assert resp[0] is not None - self.assertNamedItemInContainer(resp, 'dir1') - self.assertNamedItemInContainer(resp, 'dir2') - await self._delete_shares(share.share_name) + self.assertNamedItemInContainer(resp, "dir1") + self.assertNamedItemInContainer(resp, "dir2") + await self._delete_shares(share_name) @FileSharePreparer() @recorded_by_proxy_async @@ -1466,16 +1460,16 @@ async def test_list_directories_and_files_with_num_results(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share = await self._create_share() - await share.create_directory('dir1') - root = share.get_directory_client() - await root.upload_file('filea1', '1024') - await root.upload_file('filea2', '1024') - await root.upload_file('filea3', '1024') - await root.upload_file('fileb1', '1024') + share_name = await self._create_share() + dir1 = await share_name.create_directory("dir1") + root = share_name.get_directory_client() + await root.upload_file("filea1", "1024") + await root.upload_file("filea2", "1024") + await root.upload_file("filea3", "1024") + await root.upload_file("fileb1", "1024") # Act - result = share.list_directories_and_files(results_per_page=2).by_page() + result = share_name.list_directories_and_files(results_per_page=2).by_page() results = [] async for r in await result.__anext__(): results.append(r) @@ -1483,9 +1477,9 @@ async def test_list_directories_and_files_with_num_results(self, **kwargs): # Assert assert result is not None assert len(results) == 2 - self.assertNamedItemInContainer(results, 'dir1') - self.assertNamedItemInContainer(results, 'filea1') - await self._delete_shares(share.share_name) + self.assertNamedItemInContainer(results, "dir1") + self.assertNamedItemInContainer(results, "filea1") + await self._delete_shares(share_name) @FileSharePreparer() @recorded_by_proxy_async @@ -1494,23 +1488,23 @@ async def test_list_directories_and_files_with_num_results_and_marker(self, **kw storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - share = await self._create_share() - dir1 = share.get_directory_client('dir1') + share_name = await self._create_share() + dir1 = share_name.get_directory_client("dir1") await dir1.create_directory() - await dir1.upload_file('filea1', '1024') - await dir1.upload_file('filea2', '1024') - await dir1.upload_file('filea3', '1024') - await dir1.upload_file('fileb1', '1024') + await dir1.upload_file("filea1", "1024") + await dir1.upload_file("filea2", "1024") + await dir1.upload_file("filea3", "1024") + await dir1.upload_file("fileb1", "1024") # Act - generator1 = share.list_directories_and_files( - 'dir1', results_per_page=2).by_page() + generator1 = share_name.list_directories_and_files("dir1", results_per_page=2).by_page() result1 = [] async for r in await generator1.__anext__(): result1.append(r) - generator2 = share.list_directories_and_files( - 'dir1', results_per_page=2).by_page(continuation_token=generator1.continuation_token) + generator2 = share_name.list_directories_and_files("dir1", results_per_page=2).by_page( + continuation_token=generator1.continuation_token + ) result2 = [] async for r in await generator2.__anext__(): result2.append(r) @@ -1518,12 +1512,12 @@ async def test_list_directories_and_files_with_num_results_and_marker(self, **kw # Assert assert len(result1) == 2 assert len(result2) == 2 - self.assertNamedItemInContainer(result1, 'filea1') - self.assertNamedItemInContainer(result1, 'filea2') - self.assertNamedItemInContainer(result2, 'filea3') - self.assertNamedItemInContainer(result2, 'fileb1') + self.assertNamedItemInContainer(result1, "filea1") + self.assertNamedItemInContainer(result1, "filea2") + self.assertNamedItemInContainer(result2, "filea3") + self.assertNamedItemInContainer(result2, "fileb1") assert generator2.continuation_token == None - await self._delete_shares(share.share_name) + await self._delete_shares(share_name) @FileSharePreparer() @recorded_by_proxy_async @@ -1533,27 +1527,27 @@ async def test_list_directories_and_files_with_prefix(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = await self._create_share() - dir1 = await share.create_directory('dir1') - await share.create_directory('dir1/pref_dir3') - await share.create_directory('dir2') + dir1 = await share.create_directory("dir1") + await share.create_directory("dir1/pref_dir3") + await share.create_directory("dir2") root = share.get_directory_client() - await root.upload_file('file1', '1024') - await dir1.upload_file('pref_file2', '1025') - await dir1.upload_file('file3', '1025') + await root.upload_file("file1", "1024") + await dir1.upload_file("pref_file2", "1025") + await dir1.upload_file("file3", "1025") # Act resp = [] - async for d in share.list_directories_and_files('dir1', name_starts_with='pref'): + async for d in share.list_directories_and_files("dir1", name_starts_with="pref"): resp.append(d) # Assert assert resp is not None assert len(resp) == 2 assert resp[0] is not None - self.assertNamedItemInContainer(resp, 'pref_file2') - self.assertNamedItemInContainer(resp, 'pref_dir3') - await self._delete_shares(share.share_name) + self.assertNamedItemInContainer(resp, "pref_file2") + self.assertNamedItemInContainer(resp, "pref_dir3") + await self._delete_shares(share) @pytest.mark.live_test_only @FileSharePreparer() @@ -1562,9 +1556,9 @@ async def test_shared_access_share(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - file_name = 'file1' - dir_name = 'dir1' - data = b'hello world' + file_name = "file1" + dir_name = "dir1" + data = b"hello world" share = await self._create_share() dir1 = await share.create_directory(dir_name) @@ -1580,12 +1574,12 @@ async def test_shared_access_share(self, **kwargs): sas_client = ShareFileClient( self.account_url(storage_account_name, "file"), share_name=share.share_name, - file_path=dir_name + '/' + file_name, + file_path=dir_name + "/" + file_name, credential=token, ) # Act - response = requests.get(sas_client.url, timeout=15) + response = requests.get(sas_client.url) # Assert assert response.ok @@ -1599,9 +1593,11 @@ async def test_create_permission_for_share(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) - user_given_permission = "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" \ - "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" \ - "S-1-5-21-397955417-626881126-188441444-3053964)" + user_given_permission = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)" + ) share_client = await self._create_share() permission_key = await share_client.create_permission_for_share(user_given_permission) assert permission_key is not None @@ -1623,25 +1619,27 @@ async def test_get_permission_format(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_client = await self._create_share() - user_given_permission_sddl = ("O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" - "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" - "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL") - user_given_permission_binary = ("AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" - "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" - "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=") + user_given_permission_sddl = ( + "O:S-1-5-21-2127521184-1604012920-1887927527-21560751G:S-1-5-21-2127521184-" + "1604012920-1887927527-513D:AI(A;;FA;;;SY)(A;;FA;;;BA)(A;;0x1200a9;;;" + "S-1-5-21-397955417-626881126-188441444-3053964)S:NO_ACCESS_CONTROL" + ) + user_given_permission_binary = ( + "AQAUhGwAAACIAAAAAAAAABQAAAACAFgAAwAAAAAAFAD/AR8AAQEAAAAAAAUSAAAAAAAYAP8BHw" + "ABAgAAAAAABSAAAAAgAgAAAAAkAKkAEgABBQAAAAAABRUAAABZUbgXZnJdJWRjOwuMmS4AAQUA" + "AAAAAAUVAAAAoGXPfnhLm1/nfIdwr/1IAQEFAAAAAAAFFQAAAKBlz354S5tf53yHcAECAAA=" + ) permission_key = await share_client.create_permission_for_share(user_given_permission_sddl) assert permission_key is not None server_returned_permission = await share_client.get_permission_for_share( - permission_key, - file_permission_format="sddl" + permission_key, file_permission_format="sddl" ) assert server_returned_permission == user_given_permission_sddl server_returned_permission = await share_client.get_permission_for_share( - permission_key, - file_permission_format="binary" + permission_key, file_permission_format="binary" ) assert server_returned_permission == user_given_permission_binary @@ -1676,9 +1674,9 @@ async def test_delete_directory_from_share(self, **kwargs): self._setup(storage_account_name, storage_account_key) share = await self._create_share() - await share.create_directory('dir1') - await share.create_directory('dir2') - await share.create_directory('dir3') + await share.create_directory("dir1") + await share.create_directory("dir2") + await share.create_directory("dir3") # Act resp = [] @@ -1686,7 +1684,7 @@ async def test_delete_directory_from_share(self, **kwargs): resp.append(d) assert len(resp) == 3 - await share.delete_directory('dir3') + await share.delete_directory("dir3") # Assert resp = [] @@ -1710,9 +1708,7 @@ async def test_share_paid_bursting(self, **kwargs): # Act / Assert share = self._get_share_reference() await share.create_share( - paid_bursting_enabled=True, - paid_bursting_bandwidth_mibps=5000, - paid_bursting_iops=1000 + paid_bursting_enabled=True, paid_bursting_bandwidth_mibps=5000, paid_bursting_iops=1000 ) share_props = await share.get_share_properties() share_name = share_props.name @@ -1724,7 +1720,7 @@ async def test_share_paid_bursting(self, **kwargs): root_squash="NoRootSquash", paid_bursting_enabled=True, paid_bursting_bandwidth_mibps=mibps, - paid_bursting_iops=iops + paid_bursting_iops=iops, ) share_props = await share.get_share_properties() assert share_props.paid_bursting_enabled @@ -1754,8 +1750,8 @@ async def test_share_client_with_oauth(self, **kwargs): token_credential = self.get_credential(ShareClient, is_async=True) self._setup(storage_account_name, storage_account_key) - first_share = await self._create_share('test1') - second_share = await self._create_share('test2') + first_share = await self._create_share("test1") + second_share = await self._create_share("test2") share_names = [] async for share in self.fsc.list_shares(): @@ -1767,29 +1763,29 @@ async def test_share_client_with_oauth(self, **kwargs): self.account_url(storage_account_name, "file"), share_name=first_share.share_name, credential=token_credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) second_share_client = ShareClient( self.account_url(storage_account_name, "file"), share_name=second_share.share_name, credential=token_credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) first_share_props = await first_share_client.get_share_properties() second_share_props = await second_share_client.get_share_properties() assert first_share_props is not None assert first_share_props.name == first_share.share_name - assert first_share_props.access_tier == 'TransactionOptimized' + assert first_share_props.access_tier == "TransactionOptimized" assert second_share_props is not None assert second_share_props.name == second_share.share_name - assert second_share_props.access_tier == 'TransactionOptimized' + assert second_share_props.access_tier == "TransactionOptimized" - await first_share_client.set_share_properties(access_tier='Hot') + await first_share_client.set_share_properties(access_tier="Hot") first_share_props = await first_share_client.get_share_properties() assert first_share_props is not None assert first_share_props.name == first_share.share_name - assert first_share_props.access_tier == 'Hot' + assert first_share_props.access_tier == "Hot" share_names = [] async for share in self.fsc.list_shares(): @@ -1809,25 +1805,22 @@ async def test_share_lease_with_oauth(self, **kwargs): # Arrange self._setup(storage_account_name, storage_account_key) - share = await self._create_share('test') + share = await self._create_share("test") share_client = ShareClient( self.account_url(storage_account_name, "file"), share_name=share.share_name, credential=token_credential, - token_intent=TEST_INTENT + token_intent=TEST_INTENT, ) # Act / Assert lease_duration = 60 - lease_id = '00000000-1111-2222-3333-444444444444' - lease = await share_client.acquire_lease( - lease_id=lease_id, - lease_duration=lease_duration - ) + lease_id = "00000000-1111-2222-3333-444444444444" + lease = await share_client.acquire_lease(lease_id=lease_id, lease_duration=lease_duration) props = await share_client.get_share_properties(lease=lease) - assert props.lease.duration == 'fixed' - assert props.lease.state == 'leased' - assert props.lease.status == 'locked' + assert props.lease.duration == "fixed" + assert props.lease.state == "leased" + assert props.lease.status == "locked" await lease.renew() assert lease.id == lease_id @@ -1845,9 +1838,9 @@ async def test_create_share_access_tier_premium(self, **kwargs): self._setup(premium_storage_file_account_name, premium_storage_file_account_key) share = self._get_share_reference() - await share.create_share(access_tier='Premium') + await share.create_share(access_tier="Premium") props = await share.get_share_properties() - assert props.access_tier == 'Premium' + assert props.access_tier == "Premium" finally: await self._delete_shares() @@ -1862,9 +1855,9 @@ async def test_set_share_properties_access_tier_premium(self, **kwargs): share = self._get_share_reference() await share.create_share() - await share.set_share_properties(access_tier='Premium') + await share.set_share_properties(access_tier="Premium") props = await share.get_share_properties() - assert props.access_tier == 'Premium' + assert props.access_tier == "Premium" finally: await self._delete_shares() @@ -1892,11 +1885,7 @@ async def test_provisioned_billing_v2(self, **kwargs): assert props.next_provisioned_iops_downgrade is not None assert props.next_provisioned_bandwidth_downgrade is not None - await share.set_share_properties( - access_tier="Hot", - provisioned_iops=3000, - provisioned_bandwidth_mibps=125 - ) + await share.set_share_properties(access_tier="Hot", provisioned_iops=3000, provisioned_bandwidth_mibps=125) shares = [] async for share in self.fsc.list_shares(): @@ -1922,12 +1911,10 @@ async def test_get_user_delegation_sas(self, **kwargs): token_credential = self.get_credential(ShareServiceClient, is_async=True) service = ShareServiceClient( - self.account_url(storage_account_name, "file"), - credential=token_credential, - token_intent="backup" + self.account_url(storage_account_name, "file"), credential=token_credential, token_intent="backup" ) - start = self.get_datetime_variable(variables, 'start_time', datetime.utcnow()) - expiry = self.get_datetime_variable(variables, 'expiry_time', datetime.utcnow() + timedelta(hours=1)) + start = self.get_datetime_variable(variables, "start_time", datetime.utcnow()) + expiry = self.get_datetime_variable(variables, "expiry_time", datetime.utcnow() + timedelta(hours=1)) user_delegation_key_1 = await service.get_user_delegation_key(start=start, expiry=expiry) user_delegation_key_2 = await service.get_user_delegation_key(start=start, expiry=expiry) @@ -1953,27 +1940,23 @@ async def test_get_user_delegation_sas(self, **kwargs): @pytest.mark.live_test_only @FileSharePreparer() - async def test_share_cross_tenant_sas(self, **kwargs): # pylint: disable=too-many-locals + async def test_share_cross_tenant_sas(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") storage_account_key = kwargs.pop("storage_account_key") self._setup(storage_account_name, storage_account_key) token_credential = self.get_credential(ShareServiceClient, is_async=True) service = ShareServiceClient( - self.account_url(storage_account_name, "file"), - credential=token_credential, - token_intent="backup" + self.account_url(storage_account_name, "file"), credential=token_credential, token_intent="backup" ) start = datetime.utcnow() expiry = datetime.utcnow() + timedelta(hours=1) token = await token_credential.get_token("https://storage.azure.com/.default") - decoded = jwt.decode(token.token, options={"verify_signature": False}) # pylint: disable=no-member + decoded = jwt.decode(token.token, options={"verify_signature": False}) user_delegation_oid = decoded.get("oid") delegated_user_tid = decoded.get("tid") user_delegation_key = await service.get_user_delegation_key( - start=start, - expiry=expiry, - delegated_user_tid=delegated_user_tid + start=start, expiry=expiry, delegated_user_tid=delegated_user_tid ) assert user_delegation_key is not None @@ -1995,16 +1978,14 @@ async def test_share_cross_tenant_sas(self, **kwargs): # pylint: disable=too-ma permission=ShareSasPermissions(read=True, list=True), expiry=expiry, user_delegation_key=user_delegation_key, - user_delegation_oid=user_delegation_oid + user_delegation_oid=user_delegation_oid, ) assert "sduoid=" + user_delegation_oid in share_token assert "skdutid=" + delegated_user_tid in share_token share_client = ShareClient.from_share_url( - f"{share.url}?{share_token}", - credential=token_credential, - token_intent="backup" + f"{share.url}?{share_token}", credential=token_credential, token_intent="backup" ) structure = [] async for item in share_client.list_directories_and_files(): @@ -2020,16 +2001,14 @@ async def test_share_cross_tenant_sas(self, **kwargs): # pylint: disable=too-ma permission=FileSasPermissions(read=True), expiry=datetime.utcnow() + timedelta(hours=1), user_delegation_key=user_delegation_key, - user_delegation_oid=user_delegation_oid + user_delegation_oid=user_delegation_oid, ) assert "sduoid=" + user_delegation_oid in file_token assert "skdutid=" + delegated_user_tid in file_token file_client = ShareFileClient.from_file_url( - f"{file.url}?{file_token}", - credential=token_credential, - token_intent="backup" + f"{file.url}?{file_token}", credential=token_credential, token_intent="backup" ) content = await (await file_client.download_file()).readall() assert content == data diff --git a/sdk/storage/azure-storage-file-share/tsp-location.yaml b/sdk/storage/azure-storage-file-share/tsp-location.yaml new file mode 100644 index 000000000000..1a710edd36c7 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/storage/data-plane/FileStorage +commit: +repo: +additionalDirectories: