From 4341658a6156be2c7242ec6e15980cf9c12f7422 Mon Sep 17 00:00:00 2001 From: antisch Date: Sat, 21 Mar 2026 06:44:16 +1300 Subject: [PATCH 01/45] Initial migration --- .../azure-storage-file-share/MANIFEST.in | 6 +- .../azure-storage-file-share/_metadata.json | 6 + .../apiview-properties.json | 160 + .../azure/__init__.py | 2 +- .../azure/storage/__init__.py | 2 +- .../azure/storage/fileshare/__init__.py | 87 +- .../azure/storage/fileshare/_deserialize.py | 79 +- .../storage/fileshare/_directory_client.py | 355 +- .../fileshare/_directory_client_helpers.py | 24 +- .../azure/storage/fileshare/_download.py | 55 +- .../azure/storage/fileshare/_file_client.py | 672 +- .../storage/fileshare/_file_client_helpers.py | 100 +- .../storage/fileshare/_generated/__init__.py | 9 +- .../{_azure_file_storage.py => _client.py} | 74 +- .../fileshare/_generated/_configuration.py | 63 +- .../storage/fileshare/_generated/_patch.py | 13 +- .../fileshare/_generated/_utils/__init__.py | 2 +- .../fileshare/_generated/_utils/model_base.py | 1368 +++ .../_generated/_utils/serialization.py | 2 +- .../storage/fileshare/_generated/_version.py | 9 + .../fileshare/_generated/aio/__init__.py | 6 +- .../{_azure_file_storage.py => _client.py} | 74 +- .../_generated/aio/_configuration.py | 63 +- .../fileshare/_generated/aio/_patch.py | 13 +- .../_generated/aio/operations/__init__.py | 10 +- .../aio/operations/_directory_operations.py | 1077 --- .../aio/operations/_file_operations.py | 2591 ------ .../_generated/aio/operations/_operations.py | 5888 ++++++++++++ .../_generated/aio/operations/_patch.py | 13 +- .../aio/operations/_service_operations.py | 376 - .../aio/operations/_share_operations.py | 1811 ---- .../fileshare/_generated/models/__init__.py | 22 +- ..._azure_file_storage_enums.py => _enums.py} | 171 +- .../fileshare/_generated/models/_models.py | 2131 +++++ .../_generated/models/_models_py3.py | 1963 ---- .../fileshare/_generated/models/_patch.py | 13 +- .../_generated/operations/__init__.py | 10 +- .../operations/_directory_operations.py | 1596 ---- .../_generated/operations/_file_operations.py | 3843 -------- .../_generated/operations/_operations.py | 8048 +++++++++++++++++ .../fileshare/_generated/operations/_patch.py | 13 +- .../operations/_service_operations.py | 543 -- .../operations/_share_operations.py | 2651 ------ .../storage/fileshare/_generated/py.typed | 1 - .../azure/storage/fileshare/_lease.py | 78 +- .../azure/storage/fileshare/_models.py | 452 +- .../azure/storage/fileshare/_parser.py | 16 +- .../azure/storage/fileshare/_serialize.py | 186 +- .../azure/storage/fileshare/_share_client.py | 411 +- .../fileshare/_share_client_helpers.py | 23 +- .../fileshare/_share_service_client.py | 166 +- .../_share_service_client_helpers.py | 2 +- .../storage/fileshare/_shared/base_client.py | 98 +- .../fileshare/_shared/base_client_async.py | 4 +- .../storage/fileshare/_shared/policies.py | 38 +- .../fileshare/_shared/response_handlers.py | 8 +- .../fileshare/_shared_access_signature.py | 127 +- .../azure/storage/fileshare/_version.py | 8 +- .../azure/storage/fileshare/aio/__init__.py | 10 +- .../fileshare/aio/_directory_client_async.py | 369 +- .../storage/fileshare/aio/_download_async.py | 118 +- .../fileshare/aio/_file_client_async.py | 684 +- .../storage/fileshare/aio/_lease_async.py | 78 +- .../storage/fileshare/aio/_lease_async.pyi | 20 +- .../azure/storage/fileshare/aio/_models.py | 59 +- .../fileshare/aio/_share_client_async.py | 422 +- .../aio/_share_service_client_async.py | 174 +- .../azure/storage/fileshare/py.typed | 1 + .../azure-storage-file-share/debug_svc.py | 36 + .../azure-storage-file-share/pyproject.toml | 62 + .../samples/file_samples_authentication.py | 75 +- .../file_samples_authentication_async.py | 75 +- .../samples/file_samples_client.py | 30 +- .../samples/file_samples_client_async.py | 23 +- .../samples/file_samples_directory.py | 28 +- .../samples/file_samples_directory_async.py | 29 +- .../samples/file_samples_hello_world.py | 32 +- .../samples/file_samples_hello_world_async.py | 38 +- .../samples/file_samples_service.py | 39 +- .../samples/file_samples_service_async.py | 45 +- .../samples/file_samples_share.py | 52 +- .../samples/file_samples_share_async.py | 47 +- sdk/storage/azure-storage-file-share/setup.py | 74 +- .../tests/conftest.py | 7 +- .../tests/encryption_test_helper.py | 44 +- .../T1_legacy_tests/_test_base.py | 30 +- .../T1_legacy_tests/download.py | 9 +- .../T1_legacy_tests/download_to_file.py | 9 +- .../T1_legacy_tests/upload.py | 3 +- .../T1_legacy_tests/upload_from_file.py | 3 +- .../tests/perfstress_tests/_test_base.py | 41 +- .../tests/perfstress_tests/upload.py | 10 +- .../perfstress_tests/upload_from_file.py | 4 +- .../tests/settings/settings_fake.py | 2 +- .../tests/settings/testcase.py | 42 +- .../tests/test_directory.py | 517 +- .../tests/test_directory_async.py | 561 +- .../tests/test_file.py | 1176 +-- .../tests/test_file_api_version.py | 79 +- .../tests/test_file_api_version_async.py | 79 +- .../tests/test_file_async.py | 1266 +-- .../tests/test_file_client.py | 291 +- .../tests/test_file_client_async.py | 275 +- .../tests/test_file_service_properties.py | 63 +- .../test_file_service_properties_async.py | 49 +- .../tests/test_get_file.py | 521 +- .../tests/test_get_file_async.py | 510 +- .../tests/test_handle.py | 37 +- .../tests/test_handle_async.py | 24 +- .../tests/test_helpers.py | 27 +- .../tests/test_helpers_async.py | 29 +- .../tests/test_nfs.py | 167 +- .../tests/test_nfs_async.py | 176 +- .../tests/test_share.py | 443 +- .../tests/test_share_async.py | 425 +- .../tsp-location.yaml | 4 + 116 files changed, 24785 insertions(+), 22390 deletions(-) create mode 100644 sdk/storage/azure-storage-file-share/_metadata.json create mode 100644 sdk/storage/azure-storage-file-share/apiview-properties.json rename sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/{_azure_file_storage.py => _client.py} (61%) create mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/model_base.py create mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_version.py rename sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/{_azure_file_storage.py => _client.py} (63%) delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_directory_operations.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_file_operations.py create mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_operations.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_service_operations.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_share_operations.py rename sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/{_azure_file_storage_enums.py => _enums.py} (61%) create mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models_py3.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_directory_operations.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_file_operations.py create mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_operations.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_service_operations.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_share_operations.py delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/py.typed create mode 100644 sdk/storage/azure-storage-file-share/debug_svc.py create mode 100644 sdk/storage/azure-storage-file-share/tsp-location.yaml 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..b7d0ad5ff9ee --- /dev/null +++ b/sdk/storage/azure-storage-file-share/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersion": "2026-04-06", + "apiVersions": { + "Storage.File": "2026-04-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..7e0487b5c18f --- /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.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.StorageError": "Storage.File.Error", + "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.StorageErrorCode": "Storage.File.StorageErrorCode", + "azure.storage.fileshare.models.ShareTokenIntent": "Storage.File.ShareTokenIntent", + "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.models.FilePermissionFormat": "Storage.File.FilePermissionFormat", + "azure.storage.fileshare.models.NfsFileType": "Storage.File.NfsFileType", + "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.CopyStatusType": "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.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", + "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" + } +} \ 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..4676c4da96d3 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( + response: "PipelineResponse", obj: Any, headers: Dict[str, Any] +) -> Optional[str]: # pylint: disable=unused-argument 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( + response: "PipelineResponse", obj: Any, headers: Dict[str, Any] +) -> Optional[str]: # pylint: disable=unused-argument 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 223b7fbf6360..dcb565cfafbc 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,17 +18,14 @@ 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 AzureFileStorageClient as AzureFileStorage from ._models import DirectoryPropertiesPaged, Handle, HandlesPaged from ._parser import _datetime_to_str, _get_file_permission, _parse_snapshot 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.base_client import _NoOpCredential, _patch_generated_client from ._shared.request_handlers import add_metadata_headers from ._shared.response_handlers import process_storage_error, return_response_headers @@ -103,43 +98,48 @@ 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=self._base_url, + credential=_NoOpCredential(), 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 ) + self._client._config.allow_trailing_dot = self.allow_trailing_dot + self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot + self._client._config.file_request_intent = self.file_request_intent + self._client._config.sharesnapshot = self.snapshot + _patch_generated_client(self._client) def __enter__(self) -> Self: self._client.__enter__() @@ -159,10 +159,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 +196,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 +216,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 +250,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 +265,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 +309,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]: @@ -364,31 +393,35 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -414,7 +447,7 @@ 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) except HttpResponseError as error: @@ -484,40 +517,48 @@ 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) + **kwargs, + ) return new_directory_client except HttpResponseError as error: @@ -525,9 +566,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. @@ -567,16 +606,20 @@ 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) + **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]: @@ -594,17 +637,16 @@ 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) + **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]: @@ -628,20 +670,20 @@ 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 + **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) @@ -665,7 +707,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 @@ -675,26 +717,23 @@ 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 + **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": @@ -711,12 +750,12 @@ 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, **kwargs), + ) except HttpResponseError as error: process_storage_error(error) return response @@ -741,15 +780,16 @@ 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, **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -778,12 +818,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. @@ -833,20 +874,24 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -878,8 +923,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 @@ -907,16 +952,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. @@ -969,10 +1015,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 fd432be34b30..ef4fb6b75460 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,10 +23,9 @@ _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 AzureFileStorageClient as AzureFileStorage from ._lease import ShareLeaseClient from ._models import FileProperties, Handle, HandlesPaged from ._parser import _datetime_to_str, _get_file_permission, _parse_snapshot @@ -38,9 +35,10 @@ 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.base_client import _NoOpCredential, _patch_generated_client from ._shared.constants import DEFAULT_MAX_CONCURRENCY from ._shared.request_handlers import add_metadata_headers, get_length from ._shared.response_handlers import return_response_headers, process_storage_error @@ -50,6 +48,7 @@ from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential, TokenCredential from ._models import ContentSettings, NTFSAttributes from ._shared.base_client import StorageConfiguration +from ._shared.base_client import _NoOpCredential, _patch_generated_client def _upload_file_helper( @@ -68,7 +67,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 +82,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 +97,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,45 +160,50 @@ 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=self._base_url, + credential=_NoOpCredential(), 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 ) + self._client._config.allow_trailing_dot = self.allow_trailing_dot + self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot + self._client._config.file_request_intent = self.file_request_intent + self._client._config.sharesnapshot = self.snapshot + _patch_generated_client(self._client) def __enter__(self) -> Self: self._client.__enter__() @@ -219,10 +223,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 +265,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 +315,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 +351,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 @@ -370,13 +381,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. @@ -455,56 +467,61 @@ 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( + 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, + optional_content_length=len(data) if data is not None else None, + lease_id=access_conditions, + headers=headers, + timeout=timeout, + cls=return_response_headers, + **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. @@ -593,15 +610,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) @@ -613,9 +630,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)}") @@ -635,7 +652,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]: @@ -777,31 +795,35 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -831,25 +853,21 @@ 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, **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 @@ -912,7 +930,7 @@ 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)) return StorageStreamDownloader( client=self._client.file, @@ -920,11 +938,12 @@ 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) + **kwargs, + ) @distributed_trace def delete_file(self, **kwargs: Any) -> None: @@ -955,10 +974,10 @@ 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, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -1037,50 +1056,53 @@ 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) + **kwargs, + ) return new_file_client except HttpResponseError as error: @@ -1107,32 +1129,37 @@ 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, + **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. @@ -1194,33 +1221,37 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1252,28 +1283,27 @@ 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, + **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: @@ -1319,37 +1349,38 @@ 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, + **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. @@ -1419,11 +1450,7 @@ 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 ) try: return cast(Dict[str, Any], self._client.file.upload_range_from_url(**options)) @@ -1432,9 +1459,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. @@ -1460,25 +1485,22 @@ 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) 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. @@ -1519,7 +1541,8 @@ def get_ranges_diff( length=length, previous_sharesnapshot=previous_sharesnapshot, support_rename=include_renames, - **kwargs) + **kwargs, + ) try: ranges = self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1553,25 +1576,29 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1597,19 +1624,23 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1626,16 +1657,12 @@ 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) + self._client.file.list_handles, sharesnapshot=self.snapshot, timeout=timeout, **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]: @@ -1659,19 +1686,15 @@ 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, - marker=None, - sharesnapshot=self.snapshot, - cls=return_response_headers, - **kwargs + handle_id=handle_id, marker=None, sharesnapshot=self.snapshot, cls=return_response_headers, **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) @@ -1692,7 +1715,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 @@ -1702,33 +1725,31 @@ 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 + **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. @@ -1750,19 +1771,19 @@ 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, **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, @@ -1771,7 +1792,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. @@ -1799,28 +1820,26 @@ 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, + **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: @@ -1833,10 +1852,9 @@ 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, **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..2278527e9c1f 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) + 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) + 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..09977481fd57 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 AzureFileStorageClient # 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", + "AzureFileStorageClient", ] __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..0976b08a001c 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,26 +2,28 @@ # -------------------------------------------------------------------------- # 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 AzureFileStorageClientConfiguration 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. + +class AzureFileStorageClient: # pylint: disable=client-accepts-api-version-keyword + """Azure File Storage provides scalable file shares in the cloud using SMB and NFS protocols. :ivar service: ServiceOperations operations :vartype service: azure.storage.fileshare.operations.ServiceOperations @@ -31,45 +33,20 @@ class AzureFileStorage: # pylint: disable=client-accepts-api-version-keyword :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 :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-04-06" and None. Default value is "2026-04-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 = AzureFileStorageClientConfiguration(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) - 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..e5c597611dcd 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 AzureFileStorageClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for AzureFileStorageClient. 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-04-06" and None. Default value is "2026-04-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-04-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..87676c65a8f0 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,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/_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..a75a22adbb97 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_utils/model_base.py @@ -0,0 +1,1368 @@ +# 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: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + 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 = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + 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 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 = prop_meta.get("ns", model_meta.get("ns", None)) + 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_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: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("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} + + # if no ns for prop, use model's + 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): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + 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 = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "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: + 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": parent_meta.get("itemsNs", parent_meta.get("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: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + 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 _create_xml_element( + tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None +) -> ET.Element: + if prefix and ns: + ET.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..632a0dd26299 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 AzureFileStorageClient # type: ignore try: from ._patch import __all__ as _patch_all @@ -22,7 +22,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureFileStorage", + "AzureFileStorageClient", ] __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..9ad33aa04f97 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,26 +2,28 @@ # -------------------------------------------------------------------------- # 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 AzureFileStorageClientConfiguration 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. + +class AzureFileStorageClient: # pylint: disable=client-accepts-api-version-keyword + """Azure File Storage provides scalable file shares in the cloud using SMB and NFS protocols. :ivar service: ServiceOperations operations :vartype service: azure.storage.fileshare.aio.operations.ServiceOperations @@ -31,45 +33,20 @@ class AzureFileStorage: # pylint: disable=client-accepts-api-version-keyword :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 :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-04-06" and None. Default value is "2026-04-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 = AzureFileStorageClientConfiguration(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) - 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..efb1b5dbdf99 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 AzureFileStorageClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for AzureFileStorageClient. 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-04-06" and None. Default value is "2026-04-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-04-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..87676c65a8f0 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,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/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/__init__.py index 092b7efde334..51785ce60910 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,10 +12,10 @@ 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 ServiceOperations # type: ignore +from ._operations import ShareOperations # type: ignore +from ._operations import DirectoryOperations # type: ignore +from ._operations import FileOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * 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 76311af25265..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_file_operations.py +++ /dev/null @@ -1,2591 +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, - 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. Note it only initializes the file with no 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 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, - 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")) - - 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..f3d29a1de455 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_operations.py @@ -0,0 +1,5888 @@ +# 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 AzureFileStorageClientConfiguration + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.aio.AzureFileStorageClient`'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: AzureFileStorageClientConfiguration = 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.AzureFileStorageClient`'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: AzureFileStorageClientConfiguration = 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.StorageError, + 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.StorageError, + 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( + "str", 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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 number of input/output + operations per second (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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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 + + +class DirectoryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.aio.AzureFileStorageClient`'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: AzureFileStorageClientConfiguration = 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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["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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.AzureFileStorageClient`'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: AzureFileStorageClientConfiguration = 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, + *, + 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, + optional_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 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. + :paramtype 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 optional_content_length: Optional. Specifies the content length of the file. Default + value is None. + :paramtype optional_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( + content_length=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, + optional_content_length=optional_content_length, + content_type=content_type, + file_type=file_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.StorageError, + 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-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: Optional. Used for structured get operations. 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.StorageError, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("str", 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( + "str", 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-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")) + 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, when present, + specifies the share snapshot to query. 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.StorageError, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("str", 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( + "str", 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.StorageError, + 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.StorageError, + 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.StorageError, + 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["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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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 + 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: Optional. Used for structured put operations. Default value is + None. + :paramtype structured_body_type: str + :keyword structured_content_length: Optional. Used for structured put operations to specify + 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.StorageError, + 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[str] = None, + source_if_match_crc64: Optional[str] = None, + source_if_none_match_crc64: Optional[str] = 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: str + :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: str + :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: 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 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.StorageError, + 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("str", 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, when present, + specifies the share snapshot to query. 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.StorageError, + 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.StorageError, + 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.StorageError, + 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, when present, + specifies the share snapshot to query. 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.StorageError, + 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, when present, + specifies the share snapshot to query. 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.StorageError, + 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 file 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.StorageError, + 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. Required. 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.StorageError, + 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, when present, + specifies the share snapshot to query. 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.StorageError, + 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.StorageError, + 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 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..ff607ac9e0f8 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,17 @@ 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, FileItem, FileProperty, FileRange, FilesAndDirectoriesListSegment, HandleItem, KeyInfo, - LeaseAccessConditions, ListFilesAndDirectoriesSegmentResponse, ListHandlesResponse, ListSharesResponse, @@ -44,22 +40,22 @@ 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, DeleteSnapshotsOptionType, FileLastWrittenMode, FilePermissionFormat, FilePropertySemantics, + FileRangeWriteFromUrlType, FileRangeWriteType, LeaseDurationType, LeaseStateType, @@ -82,18 +78,14 @@ __all__ = [ "AccessPolicy", "ClearRange", - "CopyFileSmbInfo", "CorsRule", - "DestinationLeaseAccessConditions", "DirectoryItem", - "FileHTTPHeaders", "FileItem", "FileProperty", "FileRange", "FilesAndDirectoriesListSegment", "HandleItem", "KeyInfo", - "LeaseAccessConditions", "ListFilesAndDirectoriesSegmentResponse", "ListHandlesResponse", "ListSharesResponse", @@ -110,9 +102,8 @@ "ShareSmbSettingsEncryptionInTransit", "ShareStats", "SignedIdentifier", + "SignedIdentifiers", "SmbMultichannel", - "SourceLeaseAccessConditions", - "SourceModifiedAccessConditions", "StorageError", "StorageServiceProperties", "StringEncoded", @@ -123,6 +114,7 @@ "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 61% 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..82435d2f6a98 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.""" + """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..4d376d7b5ceb --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_models.py @@ -0,0 +1,2131 @@ +# 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 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: ~datetime.datetime + :ivar last_access_time: The last access time. + :vartype last_access_time: ~datetime.datetime + :ivar last_write_time: The last write time. + :vartype last_write_time: ~datetime.datetime + :ivar change_time: The change time. + :vartype change_time: ~datetime.datetime + :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[datetime.datetime] = rest_field( + name="creationTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + xml={"attribute": False, "name": "CreationTime", "text": False, "unwrapped": False}, + ) + """The creation time.""" + last_access_time: Optional[datetime.datetime] = rest_field( + name="lastAccessTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + xml={"attribute": False, "name": "LastAccessTime", "text": False, "unwrapped": False}, + ) + """The last access time.""" + last_write_time: Optional[datetime.datetime] = rest_field( + name="lastWriteTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + xml={"attribute": False, "name": "LastWriteTime", "text": False, "unwrapped": False}, + ) + """The last write time.""" + change_time: Optional[datetime.datetime] = rest_field( + name="changeTime", + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + 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="rfc3339", + 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[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, + ) -> 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="rfc3339", + 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="rfc3339", + 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="rfc3339", + 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="rfc3339", + 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="rfc3339", + 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="rfc3339", + 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="rfc3339", + 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="rfc3339", + 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 StorageError(_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 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 cors: The set of CORS rules. + :vartype cors: ~azure.storage.fileshare._generated.models.CorsRule + :ivar protocol: Protocol settings. + :vartype protocol: ~azure.storage.fileshare._generated.models.ShareProtocolSettings + """ + + 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.""" + 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.""" + protocol: Optional["_models.ShareProtocolSettings"] = rest_field( + visibility=["read", "create", "update", "delete", "query"], + xml={"attribute": False, "name": "ProtocolSettings", "text": False, "unwrapped": False}, + ) + """Protocol settings.""" + + _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, + cors: Optional[list["_models.CorsRule"]] = None, + protocol: Optional["_models.ShareProtocolSettings"] = 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: ~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 + """ + + 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: datetime.datetime = rest_field( + name="signedStart", + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + xml={"attribute": False, "name": "SignedStart", "text": False, "unwrapped": False}, + ) + """The date-time the key is active. Required.""" + signed_expiry: datetime.datetime = rest_field( + name="signedExpiry", + visibility=["read", "create", "update", "delete", "query"], + format="rfc3339", + 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: datetime.datetime, + signed_expiry: datetime.datetime, + 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..87676c65a8f0 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,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/operations/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/__init__.py index 092b7efde334..51785ce60910 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,10 +12,10 @@ 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 ServiceOperations # type: ignore +from ._operations import ShareOperations # type: ignore +from ._operations import DirectoryOperations # type: ignore +from ._operations import FileOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * 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 176dfe9bda33..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_file_operations.py +++ /dev/null @@ -1,3843 +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, - 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 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, - 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. Note it only initializes the file with no 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 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, - 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")) - - 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..b09857c988be --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_operations.py @@ -0,0 +1,8048 @@ +# 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 AzureFileStorageClientConfiguration +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_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-04-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") + 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_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-04-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-04-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-04-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 + if content_type is not None: + _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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-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-04-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-04-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) + + +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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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 + *, + 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, + optional_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: str = kwargs.pop("content_type") + 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-04-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("content_length", 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 optional_content_length is not None: + _headers["Content-Length"] = _SERIALIZER.header("optional_content_length", optional_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-04-06")) + accept = _headers.pop("Accept", "application/xml") + + # 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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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: str = kwargs.pop("content_type") + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-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["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") + 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[str] = None, + source_if_match_crc64: Optional[str] = None, + source_if_none_match_crc64: Optional[str] = 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-04-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["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, "str") + 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, "str" + ) + 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, "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") + + 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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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-04-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) + + +class ServiceOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.AzureFileStorageClient`'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: AzureFileStorageClientConfiguration = 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.AzureFileStorageClient`'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: AzureFileStorageClientConfiguration = 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.StorageError, + 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.StorageError, + 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( + "str", 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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 number of input/output + operations per second (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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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 + + +class DirectoryOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.storage.fileshare.AzureFileStorageClient`'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: AzureFileStorageClientConfiguration = 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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["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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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.AzureFileStorageClient`'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: AzureFileStorageClientConfiguration = 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, + *, + 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, + optional_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 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. + :paramtype 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 optional_content_length: Optional. Specifies the content length of the file. Default + value is None. + :paramtype optional_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( + content_length=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, + optional_content_length=optional_content_length, + content_type=content_type, + file_type=file_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.StorageError, + 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-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: Optional. Used for structured get operations. 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.StorageError, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("str", 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( + "str", 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-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")) + 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, when present, + specifies the share snapshot to query. 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.StorageError, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Last-Modified"] = self._deserialize("str", 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( + "str", 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.StorageError, + 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.StorageError, + 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.StorageError, + 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["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.StorageError, + 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.StorageError, + 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.StorageError, + 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.StorageError, + 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 + 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: Optional. Used for structured put operations. Default value is + None. + :paramtype structured_body_type: str + :keyword structured_content_length: Optional. Used for structured put operations to specify + 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.StorageError, + 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[str] = None, + source_if_match_crc64: Optional[str] = None, + source_if_none_match_crc64: Optional[str] = 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: str + :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: str + :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: 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 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.StorageError, + 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("str", 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, when present, + specifies the share snapshot to query. 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.StorageError, + 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.StorageError, + 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.StorageError, + 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, when present, + specifies the share snapshot to query. 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.StorageError, + 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, when present, + specifies the share snapshot to query. 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.StorageError, + 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 file 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.StorageError, + 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. Required. 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.StorageError, + 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, when present, + specifies the share snapshot to query. 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.StorageError, + 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.StorageError, + 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 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..87676c65a8f0 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,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/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/_generated/py.typed b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file 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..918c4f27751d 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,16 +44,15 @@ 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'): + if hasattr(client, "file_name"): self._client = client._client.file # type: ignore self._snapshot = None - elif hasattr(client, 'share_name'): + elif hasattr(client, "share_name"): self._client = client._client.share self._snapshot = client.snapshot else: @@ -90,20 +90,21 @@ 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 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, 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 +131,16 @@ 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, 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 +158,19 @@ def release(self, **kwargs: Any) -> None: """ try: if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot response = self._client.release_lease( - lease_id=self.id, - timeout=kwargs.pop('timeout', None), - cls=return_response_headers, - **kwargs) + lease_id=self.id, timeout=kwargs.pop("timeout", None), cls=return_response_headers, **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 +186,19 @@ def change(self, proposed_lease_id: str, **kwargs: Any) -> None: """ try: if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot 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), 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 +233,17 @@ 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.") response = self._client.break_lease( - timeout=kwargs.pop('timeout', None), - cls=return_response_headers, - **kwargs) + timeout=kwargs.pop("timeout", None), cls=return_response_headers, **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..cc81807580f2 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 @@ -33,15 +31,32 @@ from ._shared.models import DictMixin, get_enum_value from ._shared.response_handlers import process_storage_error, return_context_and_deserialized +import datetime as _datetime_module + if TYPE_CHECKING: from datetime import datetime from ._generated.models import ShareRootSquash +def _parse_datetime(value): + """Parse a datetime value that may already be a datetime object (new generated code) or a string (old).""" + if value is None: + return None + if isinstance(value, _datetime_module.datetime): + return value + try: + return Deserializer.deserialize_rfc(value) + except (TypeError, ValueError, AttributeError): + try: + return Deserializer.deserialize_iso(value) + except (TypeError, ValueError, AttributeError): + return value + + 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): @@ -57,13 +72,14 @@ class RetentionPolicy(GeneratedRetentionPolicy): All data older than this value will be deleted. """ - enabled: bool = False + enabled: bool """Indicates whether a retention policy is enabled for the storage service.""" - days: Optional[int] = None + days: Optional[int] """Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this value will be deleted.""" def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: + self._data = {} self.enabled = enabled self.days = days if self.enabled and (self.days is None): @@ -95,20 +111,21 @@ class Metrics(GeneratedMetrics): Determines how long the associated data should persist. """ - version: str = '1.0' + version: str """The version of Storage Analytics to configure.""" - enabled: bool = False + enabled: bool """Indicates whether metrics are enabled for the File service.""" include_apis: bool """Indicates whether metrics should generate summary statistics for called API operations.""" - retention_policy: RetentionPolicy = RetentionPolicy() + retention_policy: RetentionPolicy """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._data = {} + 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 +135,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( + generated.retention_policy + ), # pylint: disable=protected-access ) @@ -168,11 +187,12 @@ 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._data = {} + 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]]: @@ -213,6 +233,7 @@ class SmbMultichannel(GeneratedSmbMultichannel): """If SMB Multichannel is enabled.""" def __init__(self, *, enabled: bool, **kwargs: Any) -> None: + self._data = {} self.enabled = enabled @@ -226,6 +247,7 @@ class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): """If encryption in transit is enabled.""" def __init__(self, *, required: bool, **kwargs: Any) -> None: + self._data = {} self.required = required @@ -248,6 +270,7 @@ def __init__( encryption_in_transit: Optional[SmbEncryptionInTransit] = None, **kwargs: Any ) -> None: + self._data = {} self.multichannel = multichannel self.encryption_in_transit = encryption_in_transit if self.multichannel is None and self.encryption_in_transit is None: @@ -264,6 +287,7 @@ class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): """If encryption in transit is enabled.""" def __init__(self, *, required: bool, **kwargs: Any) -> None: + self._data = {} self.required = required @@ -277,6 +301,7 @@ class ShareNfsSettings(GeneratedShareNfsSettings): """Sets the encryption in transit settings.""" def __init__(self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any) -> None: + self._data = {} self.encryption_in_transit = encryption_in_transit @@ -295,12 +320,9 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): """Sets the NFS settings.""" def __init__( - self, - *, - smb: Optional[ShareSmbSettings] = None, - nfs: Optional[ShareNfsSettings] = None, - **kwargs: Any + self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any ) -> None: + self._data = {} self.smb = smb self.nfs = nfs if self.smb is None and self.nfs is None: @@ -346,22 +368,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 +399,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,10 +463,12 @@ 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._data = {} self.start = start self.expiry = expiry self.permission = permission @@ -463,9 +485,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 +538,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 +547,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 +627,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 = _parse_datetime(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 +682,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 +695,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 +728,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 +752,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 +763,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 +806,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 +856,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 +873,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 +914,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 +924,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 +936,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 +975,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 +1019,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 = _parse_datetime(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 = ( + _parse_datetime(kwargs.get("x-ms-file-change-time")) + if (kwargs.get("x-ms-file-change-time") is not None) + else None + ) + self.creation_time = ( + _parse_datetime(kwargs.get("x-ms-file-creation-time")) + if (kwargs.get("x-ms-file-creation-time") is not None) + else None + ) + self.last_write_time = ( + _parse_datetime(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 +1100,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,7 +1124,8 @@ 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) @@ -1091,8 +1134,12 @@ 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) 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 return self._response.next_marker or None, self.current_page @@ -1143,14 +1190,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 +1273,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 = _parse_datetime(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 = ( + _parse_datetime(kwargs.get("x-ms-file-change-time")) + if (kwargs.get("x-ms-file-change-time") is not None) + else None + ) + self.creation_time = ( + _parse_datetime(kwargs.get("x-ms-file-creation-time")) + if (kwargs.get("x-ms-file-creation-time") is not None) + else None + ) + self.last_write_time = ( + _parse_datetime(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 +1338,7 @@ def _from_generated(cls, generated): class ShareProtocols(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Enabled protocols on the share""" + SMB = "SMB" NFS = "NFS" @@ -1311,20 +1368,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 +1396,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 +1408,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..463dff13deac 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,10 @@ 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 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 bd157885fc8d..862d8f83057d 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,42 +16,40 @@ _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', + "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", ] 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 @@ -68,13 +59,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}'.") @@ -83,61 +74,56 @@ 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.""" 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.""" 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.""" 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) @@ -155,45 +141,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 1330b66fcf9e..f0e10d4c01a7 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,17 @@ 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 AzureFileStorageClient as AzureFileStorage +from ._generated.models import DeleteSnapshotsOptionType, ShareStats, SignedIdentifier, SignedIdentifiers from ._lease import ShareLeaseClient from ._models import ShareProtocols from ._parser import _parse_snapshot 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.base_client import _NoOpCredential, _patch_generated_client 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,40 +87,47 @@ 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=self._base_url, + credential=_NoOpCredential(), 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 ) + self._client._config.allow_trailing_dot = self.allow_trailing_dot + self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot + self._client._config.file_request_intent = self.file_request_intent + self._client._config.sharesnapshot = self.snapshot + _patch_generated_client(self._client) def __enter__(self) -> Self: self._client.__enter__() @@ -154,9 +147,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 +193,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 +237,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 +253,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 +283,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 +338,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 +391,42 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -443,23 +463,23 @@ 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, **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 +514,24 @@ 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) + **kwargs + ) except HttpResponseError as error: process_storage_error(error) @@ -546,15 +567,19 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) props.name = self.share_name @@ -594,16 +619,20 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -650,30 +679,34 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -714,17 +747,17 @@ 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, **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -750,19 +783,20 @@ 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) + timeout=timeout, cls=return_headers_and_deserialized, lease_id=access_conditions, **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 +827,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 +841,16 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -839,20 +878,20 @@ 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, **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 +940,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,7 +969,7 @@ 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)) @@ -956,13 +996,14 @@ 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, **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -992,7 +1033,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..7a046d71cf25 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 AzureFileStorageClient as AzureFileStorage from ._generated.models import KeyInfo, StorageServiceProperties from ._models import ( CorsRule, @@ -29,6 +26,7 @@ from ._share_client import ShareClient from ._share_service_client_helpers import _parse_url from ._shared.base_client import StorageAccountHostsMixin, TransportWrapper, parse_connection_str, parse_query +from ._shared.base_client import _NoOpCredential, _patch_generated_client from ._shared.parser import _to_utc_datetime from ._shared.response_handlers import parse_to_internal_user_delegation_key, process_storage_error @@ -103,36 +101,41 @@ 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=self._base_url, + credential=_NoOpCredential(), 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 ) + self._client._config.allow_trailing_dot = self.allow_trailing_dot + self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot + self._client._config.file_request_intent = self.file_request_intent + _patch_generated_client(self._client) def __enter__(self) -> Self: self._client.__enter__() @@ -162,9 +165,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 +202,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 +215,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 +239,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,7 +273,7 @@ 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) return service_properties_deserialize(service_props) @@ -280,11 +282,12 @@ def get_service_properties(self, **kwargs: Any) -> Dict[str, Any]: @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,12 +326,12 @@ 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) @@ -337,10 +340,11 @@ def set_service_properties( @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 +378,26 @@ 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) + self._client.service.list_shares_segment, include=include, timeout=timeout, **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 +431,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 +478,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 +510,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( + deleted_share_name=deleted_share_name, # pylint: disable=protected-access + 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 +551,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 5441488d86a9..364519178643 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 @@ -3,6 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- +import functools import logging import uuid from typing import ( @@ -55,6 +56,7 @@ StorageLoggingPolicy, StorageRequestHook, StorageResponseHook, + StorageTrailingSlashPolicy, ) from .request_handlers import serialize_batch_body, _get_batch_request_delimiter from .response_handlers import PartialBatchErrorException, process_storage_error @@ -75,6 +77,75 @@ } +class _NoOpCredential: + """No-op credential for the generated client when auth is handled by the convenience layer pipeline.""" + + def get_token(self, *args, **kwargs): + raise RuntimeError("This credential should not be used to get tokens directly.") + + +def _patch_generated_client(client): + """Apply workarounds to the generated client after construction. + + Wraps operation group methods to inject per-operation params from config. + """ + # Wrap operation group methods to inject per-operation params from config + # (allow_trailing_dot, allow_source_trailing_dot, file_request_intent, sharesnapshot) + # These were config-level in AutoRest but are per-operation in TypeSpec. + # For operations that accept sharesnapshot as a parameter, it's injected via kwargs. + # For operations that DON'T (e.g. download), it's injected via raw_request_hook. + import inspect + from urllib.parse import quote as _url_quote + + _per_op_params = ("allow_trailing_dot", "allow_source_trailing_dot", "file_request_intent", "sharesnapshot") + for group_name in ["service", "share", "directory", "file"]: + group = getattr(client, group_name) + for name in list(vars(type(group))): + if name.startswith("_"): + continue + method = getattr(group, name) + if not callable(method): + continue + + sig_params = set(inspect.signature(method).parameters.keys()) + inject = [p for p in _per_op_params if p in sig_params] + has_snapshot_param = "sharesnapshot" in sig_params + + # Skip methods that need no injection at all + if not inject and has_snapshot_param: + continue + if not inject and not has_snapshot_param: + # Only needs snapshot URL injection + pass + + def _make_wrapper(original, config, inject_params, _needs_snapshot_hook): + @functools.wraps(original) + def wrapper(*args, **kwargs): + for p in inject_params: + kwargs.setdefault(p, getattr(config, p, None)) + # For operations without sharesnapshot param, inject via URL hook + if _needs_snapshot_hook: + snapshot = getattr(config, "sharesnapshot", None) + if snapshot: + existing_hook = kwargs.get("raw_request_hook") + + def _snapshot_hook(request, _orig=existing_hook, _snap=snapshot): + url = request.http_request.url + if "sharesnapshot=" not in url: + sep = "&" if "?" in url else "?" + request.http_request.url = f'{url}{sep}sharesnapshot={_url_quote(_snap, safe="")}' + if _orig: + _orig(request) + + kwargs["raw_request_hook"] = _snapshot_hook + return original(*args, **kwargs) + + return wrapper + + needs_snapshot_hook = not has_snapshot_param + setattr(group, name, _make_wrapper(method, client._config, inject, needs_snapshot_hook)) + + class StorageAccountHostsMixin(object): _client: Any @@ -145,7 +216,25 @@ 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 _base_url(self) -> str: + """The endpoint URL without snapshot query parameters (for the generated client base URL). + + SAS credentials are preserved in the URL because the generated client's + operations include them in every request. Only ``sharesnapshot`` and + ``snapshot`` params are stripped — they are injected per-operation via + ``_patch_generated_client`` or by ``_InjectSnapshotPolicy``. + """ + full_url = self.url + if "?" not in full_url: + return full_url + base, qs = full_url.split("?", 1) + filtered = "&".join( + part for part in qs.split("&") if not part.startswith("sharesnapshot=") and not part.startswith("snapshot=") + ) + return f"{base}?{filtered}" if filtered else base @property def primary_endpoint(self) -> str: @@ -178,7 +267,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]: @@ -208,7 +297,7 @@ def location_mode(self) -> str: def location_mode(self, value): if self._hosts.get(value): self._location_mode = value - self._client._config.url = self.url # pylint: disable=protected-access + self._client._config.url = self._base_url # pylint: disable=protected-access else: raise ValueError(f"No host URL for location mode: {value}") @@ -280,6 +369,7 @@ def _create_pipeline( transport = RequestsTransport(**kwargs) policies = [ QueueMessagePolicy(), + StorageTrailingSlashPolicy(), config.proxy_policy, config.user_agent_policy, StorageContentValidation(), @@ -416,7 +506,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..c564639d87bf 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 @@ -40,6 +40,7 @@ StorageHeadersPolicy, StorageHosts, StorageRequestHook, + StorageTrailingSlashPolicy, ) from .policies_async import AsyncStorageBearerTokenCredentialPolicy, AsyncStorageResponseHook from .response_handlers import PartialBatchErrorException, process_storage_error @@ -128,6 +129,7 @@ def _create_pipeline( hosts = self._hosts policies = [ QueueMessagePolicy(), + StorageTrailingSlashPolicy(), config.proxy_policy, config.user_agent_policy, StorageContentValidation(), @@ -210,7 +212,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 3f65ae8d6498..f76e656b649a 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 @@ -126,6 +126,30 @@ def on_request(self, request): request.http_request.url = urljoin(request.http_request.url, message_id) +class StorageTrailingSlashPolicy(SansIOHTTPPolicy): + """Normalizes request URLs and headers for compatibility with test recordings. + + The TypeSpec-generated operations produce paths like ``/`` which, when + combined with the base URL, create a trailing slash that does not match + test-proxy recordings made with the old generated code. Also renames + the ``Range`` header to ``x-ms-range`` to match old recordings. + """ + + def on_request(self, request): + url = request.http_request.url + parsed = urlparse(url) + path = parsed.path + if len(path) > 1 and path.endswith("/"): + cleaned = parsed._replace(path=path.rstrip("/")) + request.http_request.url = urlunparse(cleaned) + + # The TypeSpec emitter uses the standard Range header, but the old + # generated code used x-ms-range. Rename for recording compatibility. + headers = request.http_request.headers + if "Range" in headers and "x-ms-range" not in headers: + headers["x-ms-range"] = headers.pop("Range") + + class StorageHeadersPolicy(HeadersPolicy): request_id_header_name = "x-ms-client-request-id" @@ -134,6 +158,10 @@ def on_request(self, request: "PipelineRequest") -> None: current_time = format_date_time(time()) request.http_request.headers["x-ms-date"] = current_time + # Ensure Accept header defaults to application/xml for Storage APIs + if "Accept" not in request.http_request.headers: + request.http_request.headers["Accept"] = "application/xml" + custom_id = request.context.options.pop("client_request_id", None) request.http_request.headers["x-ms-client-request-id"] = custom_id or str(uuid.uuid1()) @@ -438,7 +466,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. @@ -478,7 +506,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: @@ -552,7 +580,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. @@ -713,11 +741,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/response_handlers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/response_handlers.py index 9a079c56404f..cc3198a07398 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: 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 29aa028e52cb..b992dd7e5110 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.26.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 4fc04bb91d26..d2b36ac24da6 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,16 +20,13 @@ 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 .._directory_client_helpers import _format_url, _from_directory_url, _parse_url +from .._generated.aio import AzureFileStorageClient as AzureFileStorage from .._parser import _datetime_to_str, _get_file_permission, _parse_snapshot 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 +from .._shared.base_client import _NoOpCredential, _patch_generated_client from .._shared.policies_async import ExponentialRetry from .._shared.request_handlers import add_metadata_headers from .._shared.response_handlers import process_storage_error, return_response_headers @@ -104,48 +99,56 @@ 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=self._base_url, + credential=_NoOpCredential(), 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 ) + self._client._config.allow_trailing_dot = self.allow_trailing_dot + self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot + self._client._config.file_request_intent = self.file_request_intent + self._client._config.sharesnapshot = self.snapshot + _patch_generated_client(self._client) async def __aenter__(self) -> Self: await self._client.__aenter__() @@ -165,10 +168,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 +205,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 +225,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 +259,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 +275,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 +319,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]: @@ -370,31 +403,35 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -420,7 +457,7 @@ 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) except HttpResponseError as error: @@ -490,40 +527,48 @@ 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) + **kwargs, + ) return new_directory_client except HttpResponseError as error: @@ -531,9 +576,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. @@ -573,16 +616,20 @@ 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) + **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"]: @@ -600,17 +647,16 @@ 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) + **kwargs, + ) + return AsyncItemPaged(command, results_per_page=results_per_page, page_iterator_class=HandlesPaged) @distributed_trace_async async def exists(self, **kwargs: Any) -> bool: @@ -656,20 +702,20 @@ 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 + **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) @@ -693,7 +739,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 @@ -703,26 +749,23 @@ 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 + **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": @@ -739,12 +782,14 @@ 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, **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) return response @@ -769,26 +814,28 @@ 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, **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. @@ -838,20 +885,24 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -883,8 +934,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 @@ -912,16 +963,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. @@ -974,10 +1026,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 1ea648202ecc..93e2c6b8e58f 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,10 +41,9 @@ _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 .._generated.aio import AzureFileStorageClient as AzureFileStorage from .._parser import _datetime_to_str, _get_file_permission, _parse_snapshot from .._serialize import ( get_access_conditions, @@ -39,10 +51,11 @@ 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 +from .._shared.base_client import _NoOpCredential, _patch_generated_client from .._shared.constants import DEFAULT_MAX_CONCURRENCY from .._shared.policies_async import ExponentialRetry from .._shared.request_handlers import add_metadata_headers, get_length @@ -75,20 +88,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 +118,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,50 +177,58 @@ 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=self._base_url, + credential=_NoOpCredential(), 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 ) + self._client._config.allow_trailing_dot = self.allow_trailing_dot + self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot + self._client._config.file_request_intent = self.file_request_intent + self._client._config.sharesnapshot = self.snapshot + _patch_generated_client(self._client) async def __aenter__(self) -> Self: await self._client.__aenter__() @@ -225,10 +248,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 +290,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 +340,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 +367,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 @@ -367,13 +397,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. @@ -450,57 +481,61 @@ 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( + 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, + optional_content_length=len(data) if data is not None else None, + lease_id=access_conditions, + headers=headers, + timeout=timeout, + cls=return_response_headers, + **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. @@ -587,15 +622,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) @@ -611,7 +646,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)}") @@ -631,7 +666,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]: @@ -773,32 +809,35 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -828,24 +867,20 @@ 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, **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 @@ -911,7 +946,7 @@ 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)) downloader = StorageStreamDownloader( client=self._client.file, @@ -919,11 +954,11 @@ 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 + **kwargs, ) await downloader._setup() # pylint: disable=protected-access return downloader @@ -957,10 +992,10 @@ 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, **kwargs) except HttpResponseError as error: process_storage_error(error) @@ -1039,50 +1074,53 @@ 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) + **kwargs, + ) return new_file_client except HttpResponseError as error: @@ -1109,16 +1147,19 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) file_props.name = self.file_name @@ -1129,13 +1170,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. @@ -1195,34 +1237,37 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1254,25 +1299,27 @@ 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, + **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: @@ -1318,37 +1365,37 @@ 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, + **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. @@ -1418,11 +1465,7 @@ 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 ) try: return cast(Dict[str, Any], await self._client.file.upload_range_from_url(**options)) @@ -1431,9 +1474,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. @@ -1459,25 +1500,22 @@ 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) 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. @@ -1518,7 +1556,8 @@ async def get_ranges_diff( length=length, previous_sharesnapshot=previous_sharesnapshot, support_rename=include_renames, - **kwargs) + **kwargs, + ) try: ranges = await self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1552,8 +1591,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") @@ -1562,16 +1601,19 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1597,20 +1639,23 @@ 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, + **kwargs, + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -1627,16 +1672,12 @@ 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) + self._client.file.list_handles, sharesnapshot=self.snapshot, timeout=timeout, **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]: @@ -1660,19 +1701,15 @@ 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, - marker=None, - sharesnapshot=self.snapshot, - cls=return_response_headers, - **kwargs + handle_id=handle_id, marker=None, sharesnapshot=self.snapshot, cls=return_response_headers, **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) @@ -1694,7 +1731,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 @@ -1704,33 +1741,31 @@ 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 + **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. @@ -1752,19 +1787,19 @@ 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, **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, @@ -1773,7 +1808,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. @@ -1801,28 +1836,26 @@ 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, + **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: @@ -1835,10 +1868,9 @@ 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, **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..0697b433db8a 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,16 +54,15 @@ 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'): + if hasattr(client, "file_name"): self._client = client._client.file # type: ignore self._snapshot = None - elif hasattr(client, 'share_name'): + elif hasattr(client, "share_name"): self._client = client._client.share self._snapshot = client.snapshot else: @@ -100,20 +100,21 @@ 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 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, 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 +141,16 @@ 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, 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 +168,19 @@ async def release(self, **kwargs: Any) -> None: """ try: if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot response = await self._client.release_lease( - lease_id=self.id, - timeout=kwargs.pop('timeout', None), - cls=return_response_headers, - **kwargs) + lease_id=self.id, timeout=kwargs.pop("timeout", None), cls=return_response_headers, **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 +196,19 @@ async def change(self, proposed_lease_id: str, **kwargs: Any) -> None: """ try: if self._snapshot: - kwargs['sharesnapshot'] = self._snapshot + kwargs["sharesnapshot"] = self._snapshot 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), 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 +243,17 @@ 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.") response = await self._client.break_lease( - timeout=kwargs.pop('timeout', None), - cls=return_response_headers, - **kwargs) + timeout=kwargs.pop("timeout", None), cls=return_response_headers, **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..0aa13391ef2d 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,10 @@ 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) 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 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 2d2cdaf0a3f0..326d2df49918 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,17 @@ 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 AzureFileStorageClient 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 .._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.base_client import _NoOpCredential, _patch_generated_client 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,45 +88,55 @@ 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=self._base_url, + credential=_NoOpCredential(), 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 ) + self._client._config.allow_trailing_dot = self.allow_trailing_dot + self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot + self._client._config.file_request_intent = self.file_request_intent + self._client._config.sharesnapshot = self.snapshot + _patch_generated_client(self._client) async def __aenter__(self) -> Self: await self._client.__aenter__() @@ -160,9 +156,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 +202,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 +246,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 +262,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 +292,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 +338,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 +391,42 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -438,23 +463,23 @@ 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, **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 +513,24 @@ 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, + **kwargs + ) except HttpResponseError as error: process_storage_error(error) @@ -540,15 +566,19 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) props.name = self.share_name @@ -588,16 +618,20 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -644,30 +678,34 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -708,17 +746,17 @@ 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, **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -744,25 +782,25 @@ 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) + timeout=timeout, cls=return_headers_and_deserialized, lease_id=access_conditions, **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 +828,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 +842,16 @@ 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, + **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -836,20 +879,21 @@ 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, **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 +942,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,7 +970,7 @@ 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)) @@ -952,13 +997,14 @@ 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, **kwargs + ), + ) except HttpResponseError as error: process_storage_error(error) @@ -988,7 +1034,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..a17a2872381b 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,13 +16,14 @@ 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 AzureFileStorageClient as AzureFileStorage from .._generated.models import KeyInfo, StorageServiceProperties from .._models import CorsRule, service_properties_deserialize, ShareProperties from .._serialize import get_api_version from .._share_service_client_helpers import _parse_url from .._shared.base_client import StorageAccountHostsMixin, parse_query from .._shared.base_client_async import AsyncStorageAccountHostsMixin, AsyncTransportWrapper, parse_connection_str +from .._shared.base_client import _NoOpCredential, _patch_generated_client from .._shared.parser import _to_utc_datetime from .._shared.policies_async import ExponentialRetry from .._shared.response_handlers import parse_to_internal_user_delegation_key, process_storage_error @@ -100,42 +98,50 @@ 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=self._base_url, + credential=_NoOpCredential(), 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 ) + self._client._config.allow_trailing_dot = self.allow_trailing_dot + self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot + self._client._config.file_request_intent = self.file_request_intent + _patch_generated_client(self._client) async def __aenter__(self) -> Self: await self._client.__aenter__() @@ -165,9 +171,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 +208,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 +221,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 +245,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,7 +279,7 @@ 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) return service_properties_deserialize(service_props) @@ -283,11 +288,12 @@ async def get_service_properties(self, **kwargs: Any) -> Dict[str, Any]: @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,12 +332,12 @@ 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) @@ -340,10 +346,11 @@ async def set_service_properties( @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 +384,26 @@ 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) + self._client.service.list_shares_segment, include=include, timeout=timeout, **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 +437,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 +484,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 +515,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( + deleted_share_name=deleted_share_name, # pylint: disable=protected-access + 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 +557,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/debug_svc.py b/sdk/storage/azure-storage-file-share/debug_svc.py new file mode 100644 index 000000000000..b40354b062ba --- /dev/null +++ b/sdk/storage/azure-storage-file-share/debug_svc.py @@ -0,0 +1,36 @@ +import sys +import azure.storage.fileshare._models as models + +orig_deserialize = models.service_properties_deserialize + + +def debug_deserialize(generated): + print(f"DEBUG generated type: {type(generated)}", file=sys.stderr) + if hasattr(generated, "hour_metrics"): + hm = generated.hour_metrics + print(f"DEBUG hour_metrics type: {type(hm)}", file=sys.stderr) + if hm: + data = getattr(hm, "_data", "NO _data") + print(f"DEBUG hm._data: {data}", file=sys.stderr) + rp = getattr(hm, "retention_policy", "NO retention_policy") + print(f"DEBUG retention_policy: {type(rp)} = {rp}", file=sys.stderr) + return orig_deserialize(generated) + + +models.service_properties_deserialize = debug_deserialize +import azure.storage.fileshare._share_service_client as ssc + +ssc.service_properties_deserialize = debug_deserialize + +import pytest + +pytest.main( + [ + "-x", + "tests/test_file_service_properties.py::TestFileServiceProperties::test_file_service_properties", + "-q", + "--tb=short", + "--no-header", + "-s", + ] +) diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index 08a774b6e206..2f1582cfc5b8 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -1,3 +1,65 @@ +# -------------------------------------------------------------------------- +# 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 = "azpysdkhelp@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.37.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[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 a4eeb424e463..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,35 +138,36 @@ 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() sample.authentication_shared_access_signature() sample.authentication_default_azure_credential() - 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 98cc9db0a6f3..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,10 +153,8 @@ 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() sample.acquire_file_lease() - - 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 2fbc65c80774..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,9 +129,8 @@ 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() sample.get_share_client() - 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 index 2e62c6db6a86..a2c056d3a311 100644 --- a/sdk/storage/azure-storage-file-share/setup.py +++ b/sdk/storage/azure-storage-file-share/setup.py @@ -1,10 +1,10 @@ #!/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 @@ -17,60 +17,56 @@ PACKAGE_PPRINT_NAME = "Azure File Share Storage" # a.b.c => a/b/c -package_folder_path = NAMESPACE_NAME.replace('.', '/') +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) +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') + raise RuntimeError("Cannot find version information") -with open('README.md', encoding='utf-8') as f: +with open("README.md", encoding="utf-8") as f: readme = f.read() -with open('CHANGELOG.md', encoding='utf-8') as f: +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', + 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', + "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', - ]), + 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" - ], + 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 66cd7dd21ae2..d29d472cef15 100644 --- a/sdk/storage/azure-storage-file-share/tests/conftest.py +++ b/sdk/storage/azure-storage-file-share/tests/conftest.py @@ -15,9 +15,11 @@ add_header_regex_sanitizer, add_oauth_response_sanitizer, add_uri_string_sanitizer, - test_proxy + set_custom_default_matcher, + 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") @@ -33,3 +35,6 @@ 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) 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 a452a1071c87..99d462050843 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 @@ -17,26 +17,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 @@ -54,37 +54,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 8b37a0d5f83b..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 @@ -10,6 +10,7 @@ from azure.storage.file import FileService + class _LegacyServiceTest(PerfStressTest): service_client = None async_service_client = None @@ -27,10 +28,31 @@ def __init__(self, arguments): @staticmethod def add_arguments(parser): super(_LegacyServiceTest, _LegacyServiceTest).add_arguments(parser) - parser.add_argument('-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) - parser.add_argument('-c', '--max-concurrency', nargs='?', type=int, 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) - 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) + parser.add_argument( + "-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, + ) + parser.add_argument( + "-c", + "--max-concurrency", + nargs="?", + type=int, + 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 + ) + 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, + ) class _LegacyShareTest(_LegacyServiceTest): 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 24ed6988f36e..bb23d1ee960f 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 8b612b0ef096..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 @@ -21,12 +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) - _ServiceTest.async_service_client = AsyncShareServiceClient.from_connection_string(conn_str=connection_string, **kwargs) + _ServiceTest.service_client = SyncShareServiceClient.from_connection_string( + conn_str=connection_string, **kwargs + ) + _ServiceTest.async_service_client = AsyncShareServiceClient.from_connection_string( + 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() @@ -35,10 +39,31 @@ async def close(self): @staticmethod def add_arguments(parser): super(_ServiceTest, _ServiceTest).add_arguments(parser) - parser.add_argument('-r', '--max-range-size', nargs='?', type=int, help='Maximum size of data uploading in single HTTP PUT. Defaults to SDK default.', default=None) - parser.add_argument('-c', '--max-concurrency', nargs='?', type=int, 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) - 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) + parser.add_argument( + "-r", + "--max-range-size", + nargs="?", + type=int, + help="Maximum size of data uploading in single HTTP PUT. Defaults to SDK default.", + default=None, + ) + parser.add_argument( + "-c", + "--max-concurrency", + nargs="?", + type=int, + 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 + ) + 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, + ) class _ShareTest(_ServiceTest): 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 116cb4498d73..d0407b0c8bbe 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 7e5a94151067..99aab3531ddc 100644 --- a/sdk/storage/azure-storage-file-share/tests/settings/testcase.py +++ b/sdk/storage/azure-storage-file-share/tests/settings/testcase.py @@ -17,8 +17,9 @@ 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 + from cStringIO import StringIO # Python 2 except ImportError: from io import StringIO @@ -35,34 +36,45 @@ 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 +) -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 +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", premium_storage_file_account_key=STORAGE_ACCOUNT_FAKE_KEY, secondary_storage_account_name="pyrmtstoragestorname", secondary_storage_account_key=STORAGE_ACCOUNT_FAKE_KEY, - options=EnvironmentVariableOptions(hide_secrets=["storage_account_key", "secondary_storage_account_key", "premium_storage_file_account_key"]), + options=EnvironmentVariableOptions( + hide_secrets=["storage_account_key", "secondary_storage_account_key", "premium_storage_file_account_key"] + ), ) 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 d5e59e77beef..d1df3132d787 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 @@ -21,10 +22,13 @@ 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" @@ -33,7 +37,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: @@ -47,6 +51,7 @@ def _teardown(self, FILE_PATH): os.remove(FILE_PATH) except: pass + # --Helpers----------------------------------------------------------------- # --Test cases for directories ---------------------------------------------- @@ -60,7 +65,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 @@ -73,10 +78,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 @@ -92,9 +97,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 @@ -108,16 +113,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) + file_creation_time = file_last_write_time = file_change_time = datetime( + 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 @@ -125,8 +133,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 @@ -139,10 +147,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() @@ -158,20 +168,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 @@ -181,14 +193,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 @@ -198,15 +210,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 @@ -218,19 +230,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 @@ -239,10 +251,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) @@ -258,9 +270,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 @@ -279,7 +291,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") @@ -294,15 +306,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() @@ -314,7 +326,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() @@ -335,10 +347,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() @@ -358,14 +372,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 @@ -383,10 +397,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() @@ -406,14 +422,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 @@ -428,7 +444,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): @@ -444,7 +460,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() @@ -460,7 +476,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): @@ -476,7 +492,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: @@ -493,13 +509,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 @@ -514,11 +530,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() @@ -533,8 +549,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) @@ -553,11 +569,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() @@ -575,7 +593,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 @@ -599,10 +617,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() @@ -617,10 +637,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() @@ -638,7 +658,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 @@ -652,11 +672,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 @@ -674,10 +695,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() @@ -692,11 +715,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 @@ -713,7 +737,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") @@ -726,18 +750,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 @@ -750,10 +774,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() @@ -769,18 +795,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 @@ -791,10 +817,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.") @@ -804,12 +832,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 @@ -819,7 +847,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") @@ -828,10 +856,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 @@ -841,7 +869,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") @@ -850,10 +878,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 @@ -863,7 +891,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") @@ -872,7 +900,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 @@ -895,7 +925,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)) @@ -912,7 +942,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") @@ -925,12 +955,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 @@ -940,7 +970,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") @@ -951,20 +981,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 @@ -974,7 +1004,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") @@ -987,11 +1017,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 @@ -1008,11 +1038,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}" @@ -1025,7 +1055,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() @@ -1046,10 +1076,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() @@ -1070,10 +1102,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() @@ -1092,7 +1126,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): @@ -1108,7 +1142,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() @@ -1128,10 +1162,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() @@ -1148,14 +1182,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() @@ -1170,13 +1206,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 @@ -1192,17 +1228,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() @@ -1219,10 +1255,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() @@ -1238,12 +1274,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() @@ -1259,7 +1295,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) @@ -1268,17 +1304,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), 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 @@ -1292,15 +1329,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() @@ -1322,16 +1359,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() @@ -1345,14 +1382,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() @@ -1371,20 +1410,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 @@ -1401,20 +1442,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=f'https://badaudience.file.core.windows.net' + audience=f"https://badaudience.file.core.windows.net", ) # Assert @@ -1428,55 +1471,51 @@ 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 new_directory_client.delete_directory() + # ------------------------------------------------------------------------------ -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 aab82f8447bd..fdbac2a0e371 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 # ------------------------------------------------------------------------- @@ -11,12 +12,7 @@ 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 import generate_share_sas, NTFSAttributes, ShareSasPermissions, StorageErrorCode from azure.storage.fileshare.aio import ShareDirectoryClient, ShareServiceClient from devtools_testutils.aio import recorded_by_proxy_async @@ -24,9 +20,11 @@ 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 +34,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) @@ -62,7 +60,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 @@ -76,10 +74,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() @@ -96,9 +94,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 @@ -113,16 +111,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 @@ -130,8 +131,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 @@ -145,10 +146,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() @@ -165,20 +168,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 @@ -189,15 +194,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 @@ -208,15 +212,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 @@ -228,11 +232,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 = [] @@ -241,8 +245,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 @@ -252,10 +256,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) @@ -273,9 +277,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 @@ -295,15 +299,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() @@ -316,7 +320,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() @@ -338,10 +342,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() @@ -362,14 +368,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 @@ -388,10 +394,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() @@ -412,14 +420,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 @@ -435,7 +443,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): @@ -451,7 +459,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") @@ -469,7 +477,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() @@ -486,7 +494,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): @@ -503,7 +511,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: @@ -521,13 +529,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 @@ -543,11 +551,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() @@ -563,8 +571,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) @@ -584,11 +592,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() @@ -607,7 +617,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 @@ -631,10 +641,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() @@ -649,10 +661,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() @@ -671,7 +683,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 @@ -685,11 +697,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 @@ -707,10 +720,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() @@ -725,11 +740,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 @@ -746,14 +762,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 = [] @@ -763,21 +780,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 @@ -791,10 +808,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() @@ -804,7 +823,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 = [] @@ -814,21 +834,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 @@ -840,15 +860,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 @@ -858,12 +880,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 @@ -874,10 +896,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 = [] @@ -886,10 +908,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 @@ -900,10 +922,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 = [] @@ -912,10 +934,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 @@ -926,18 +948,21 @@ 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 = [] - async for d in directory.list_directories_and_files(include=["timestamps", "Etag", "Attributes", "PermissionKey"]): + async for d in directory.list_directories_and_files( + include=["timestamps", "Etag", "Attributes", "PermissionKey"] + ): list_dir.append(d) assert len(list_dir) == 6 @@ -963,9 +988,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 = [] @@ -986,14 +1010,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 = [] @@ -1002,12 +1027,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 @@ -1018,20 +1043,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 = [] @@ -1040,13 +1067,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 @@ -1057,14 +1084,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 = [] @@ -1073,11 +1101,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 @@ -1096,9 +1124,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 @@ -1114,7 +1140,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() @@ -1136,10 +1162,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() @@ -1161,10 +1189,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() @@ -1184,7 +1214,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): @@ -1201,7 +1231,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() @@ -1222,10 +1252,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() @@ -1243,14 +1273,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() @@ -1266,13 +1298,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 @@ -1289,17 +1321,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() @@ -1317,10 +1349,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() @@ -1337,12 +1369,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() @@ -1359,7 +1391,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) @@ -1368,17 +1400,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 @@ -1393,15 +1426,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() @@ -1424,16 +1457,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() @@ -1448,14 +1481,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() @@ -1474,20 +1509,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 @@ -1504,20 +1541,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=f'https://badaudience.file.core.windows.net' + audience=f"https://badaudience.file.core.windows.net", ) # Assert @@ -1531,17 +1570,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() @@ -1549,8 +1590,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() @@ -1558,26 +1598,23 @@ 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 await new_directory_client.delete_directory() + # ------------------------------------------------------------------------------ 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 72104b1b7efd..c9e23f61874e 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 @@ -11,7 +12,12 @@ import requests from azure.core import MatchConditions from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential -from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, +) from azure.storage.blob import BlobServiceClient from azure.storage.fileshare import ( AccessPolicy, @@ -26,7 +32,7 @@ ShareFileClient, ShareSasPermissions, ShareServiceClient, - StorageErrorCode + StorageErrorCode, ) from devtools_testutils import recorded_by_proxy @@ -35,14 +41,16 @@ 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" # ------------------------------------------------------------------------------ @@ -59,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) @@ -94,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): @@ -111,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() @@ -121,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) @@ -133,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() @@ -171,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 @@ -187,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 @@ -196,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") @@ -205,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 @@ -215,19 +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 @@ -241,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() @@ -261,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") @@ -272,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 @@ -289,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) @@ -300,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 @@ -333,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) @@ -346,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 @@ -361,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) @@ -372,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( @@ -382,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 @@ -403,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) @@ -417,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() @@ -428,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) @@ -443,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 @@ -485,7 +502,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.secret + credential=storage_account_key.secret, ) file1.create_file(1024, file_property_semantics=None) props = file1.get_file_properties() @@ -495,7 +512,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.secret + credential=storage_account_key.secret, ) file2.create_file(1024, file_property_semantics="New") props = file2.get_file_properties() @@ -505,7 +522,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.secret + credential=storage_account_key.secret, ) file3.create_file(1024, file_property_semantics="Restore", file_permission=TEST_FILE_PERMISSIONS) props = file3.get_file_properties() @@ -521,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 @@ -546,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 @@ -570,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): @@ -597,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): @@ -624,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): @@ -649,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 @@ -681,7 +701,9 @@ def test_create_file_set_smb_properties(self, **kwargs): file_client = self._get_file_client() 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) + file_creation_time = file_last_write_time = file_change_time = datetime( + 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc + ) # Act file_client.create_file( @@ -689,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 @@ -697,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 @@ -727,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): @@ -753,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 @@ -804,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): @@ -834,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): @@ -855,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 @@ -891,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() @@ -912,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 @@ -930,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 @@ -942,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) @@ -957,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 @@ -984,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 @@ -1029,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) @@ -1050,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 @@ -1060,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() @@ -1078,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() @@ -1114,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 @@ -1141,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) @@ -1166,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): @@ -1197,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 @@ -1206,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 @@ -1225,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) @@ -1235,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 @@ -1248,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 @@ -1262,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) @@ -1273,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) @@ -1287,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 @@ -1322,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) @@ -1343,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 @@ -1367,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): @@ -1385,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 @@ -1405,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() @@ -1420,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 @@ -1430,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) @@ -1455,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 @@ -1471,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() @@ -1491,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 @@ -1509,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 @@ -1523,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 @@ -1537,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): @@ -1554,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 @@ -1570,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() @@ -1595,15 +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 @@ -1612,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( @@ -1629,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() @@ -1659,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 @@ -1677,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() @@ -1700,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 @@ -1715,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 @@ -1734,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 @@ -1749,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 @@ -1775,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() @@ -1789,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 @@ -1800,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 @@ -1814,10 +1870,10 @@ def test_update_file_unicode(self, **kwargs): file_client = self._create_file() # Act - data = u'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() @@ -1838,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 @@ -1859,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 @@ -1871,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 @@ -1885,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() @@ -1913,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) @@ -1925,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 @@ -1933,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 @@ -1962,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) @@ -1974,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 @@ -1982,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 @@ -2008,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) @@ -2022,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 @@ -2031,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 @@ -2060,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) @@ -2071,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): @@ -2084,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 @@ -2099,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) @@ -2112,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 @@ -2129,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) @@ -2139,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() @@ -2164,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) @@ -2175,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() @@ -2198,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) @@ -2211,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() @@ -2221,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 @@ -2237,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 @@ -2263,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 @@ -2289,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 @@ -2324,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): @@ -2337,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 @@ -2354,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) @@ -2368,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 @@ -2385,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) @@ -2408,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 @@ -2434,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 @@ -2463,17 +2538,23 @@ def test_copy_file_async_private_file(self, **kwargs): secondary_storage_account_name = kwargs.pop("secondary_storage_account_name") secondary_storage_account_key = kwargs.pop("secondary_storage_account_key") - self._setup(storage_account_name, storage_account_key, secondary_storage_account_name, secondary_storage_account_key.secret) + self._setup( + storage_account_name, + storage_account_key, + secondary_storage_account_name, + 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) @@ -2487,8 +2568,13 @@ def test_copy_file_async_private_file_with_sas(self, **kwargs): storage_account_key = kwargs.pop("storage_account_key") secondary_storage_account_name = kwargs.pop("secondary_storage_account_name") secondary_storage_account_key = kwargs.pop("secondary_storage_account_key") - self._setup(storage_account_name, storage_account_key, secondary_storage_account_name, secondary_storage_account_key.secret) - data = b'12345678' * 1024 + self._setup( + storage_account_name, + storage_account_key, + secondary_storage_account_name, + secondary_storage_account_key.secret, + ) + data = b"12345678" * 1024 self._create_remote_share() source_file = self._create_remote_file(file_data=data) sas_token = self.generate_sas( @@ -2500,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() @@ -2526,8 +2613,13 @@ def test_abort_copy_file(self, **kwargs): secondary_storage_account_name = kwargs.pop("secondary_storage_account_name") secondary_storage_account_key = kwargs.pop("secondary_storage_account_key") - 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( @@ -2539,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() @@ -2566,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( @@ -2580,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 @@ -2609,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 @@ -2630,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 @@ -2651,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 @@ -2686,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 = u'hello world啊齄丂狛狜'.encode('utf-8') + data = "hello world啊齄丂狛狜".encode("utf-8") file_client.upload_file(data) # Assert @@ -2706,14 +2808,14 @@ def test_file_unicode_data_and_file_attributes(self, **kwargs): file_client = self._get_file_client() # Act - data = u'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 @@ -2722,7 +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+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==' + 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() @@ -2730,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 @@ -2753,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) @@ -2786,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:]) @@ -2813,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() @@ -2838,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: @@ -2846,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) @@ -2866,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)) @@ -2881,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) @@ -2902,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) @@ -2911,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]) @@ -2931,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) @@ -2958,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)) @@ -2992,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 @@ -3018,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)) @@ -3046,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 = u'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) @@ -3069,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 = u'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) @@ -3093,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) @@ -3121,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) @@ -3142,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) @@ -3163,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 @@ -3189,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 @@ -3224,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 @@ -3235,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( @@ -3256,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() @@ -3292,7 +3416,8 @@ 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) @@ -3322,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() @@ -3335,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) @@ -3345,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() @@ -3361,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() @@ -3386,7 +3513,8 @@ 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) + credential=token, + ) response = requests.get(file_client.url) # Assert @@ -3409,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 @@ -3421,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) + 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() @@ -3439,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, @@ -3454,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) + 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() @@ -3486,7 +3616,8 @@ 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) @@ -3503,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 @@ -3527,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 @@ -3547,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 @@ -3568,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) @@ -3579,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 @@ -3593,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() @@ -3613,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() @@ -3634,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) @@ -3643,16 +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), 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 @@ -3664,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() @@ -3685,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 @@ -3717,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 @@ -3746,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) @@ -3761,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 @@ -3781,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) @@ -3796,7 +3925,7 @@ def test_bad_audience_file_client(self, **kwargs): file_path=file_name, credential=token_credential, token_intent=TEST_INTENT, - audience=f'https://badaudience.file.core.windows.net' + audience=f"https://badaudience.file.core.windows.net", ) # Assert @@ -3810,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 @@ -3831,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 @@ -3862,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 @@ -3871,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() @@ -3900,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() @@ -3930,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!" @@ -3949,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" @@ -3979,11 +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\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) @@ -4006,8 +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\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) @@ -4028,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" @@ -4050,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) @@ -4060,4 +4177,5 @@ def test_download_file_with_none_max_concurrency(self, **kwargs): assert content == 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 0f05f1543337..60c12fe81e25 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 @@ -14,7 +14,7 @@ from settings.testcase import FileSharePreparer # ------------------------------------------------------------------------------ -TEST_FILE_PREFIX = 'file' +TEST_FILE_PREFIX = "file" class TestStorageClient(StorageRecordedTestCase): @@ -29,7 +29,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() @@ -44,14 +44,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 @@ -59,9 +56,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 @@ -71,10 +67,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 @@ -82,7 +75,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 @@ -97,10 +91,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 @@ -109,7 +101,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 @@ -124,10 +117,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 @@ -136,25 +127,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: @@ -163,7 +150,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: @@ -172,7 +160,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() @@ -186,7 +175,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() @@ -194,19 +183,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) @@ -214,13 +204,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 bb347918073a..db495816cdbb 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 @@ -14,7 +14,7 @@ from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase # ------------------------------------------------------------------------------ -TEST_FILE_PREFIX = 'file' +TEST_FILE_PREFIX = "file" class TestAsyncStorageClient(AsyncStorageRecordedTestCase): @@ -29,7 +29,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() @@ -44,14 +44,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 @@ -59,9 +56,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 @@ -71,10 +67,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 @@ -82,7 +75,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 @@ -97,10 +91,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 @@ -109,7 +101,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 @@ -124,10 +117,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 @@ -136,25 +127,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: @@ -163,7 +150,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: @@ -172,7 +160,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() @@ -187,7 +176,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() @@ -195,19 +184,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) @@ -215,13 +205,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 0fd265019a4b..e1a7277e82ec 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 @@ -13,7 +14,12 @@ import pytest import requests from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential -from azure.core.exceptions import ClientAuthenticationError, 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, @@ -26,7 +32,7 @@ NTFSAttributes, ResourceTypes, ShareSasPermissions, - StorageErrorCode + StorageErrorCode, ) from azure.storage.fileshare.aio import ShareFileClient, ShareServiceClient @@ -36,14 +42,16 @@ 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" # ------------------------------------------------------------------------------ @@ -57,11 +65,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") @@ -87,15 +94,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) @@ -126,7 +134,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() @@ -136,7 +144,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) @@ -148,13 +156,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) @@ -187,7 +195,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 @@ -203,7 +211,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 @@ -212,7 +220,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") @@ -221,7 +229,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 @@ -231,19 +239,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 @@ -258,7 +266,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() @@ -279,7 +288,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) @@ -287,8 +297,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 @@ -301,19 +311,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 @@ -332,7 +343,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() @@ -345,20 +356,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 @@ -372,9 +384,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) @@ -383,9 +396,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( @@ -393,17 +407,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 @@ -415,13 +430,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) @@ -429,8 +445,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() @@ -441,24 +457,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 @@ -498,7 +515,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.secret + credential=storage_account_key.secret, ) await file1.create_file(1024, file_property_semantics=None) props = await file1.get_file_properties() @@ -508,7 +525,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.secret + credential=storage_account_key.secret, ) await file2.create_file(1024, file_property_semantics="New") props = await file2.get_file_properties() @@ -518,7 +535,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.secret + 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() @@ -534,7 +551,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 @@ -560,10 +577,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 @@ -584,9 +602,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): @@ -612,12 +630,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): @@ -640,14 +659,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): @@ -665,7 +685,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 @@ -697,7 +717,9 @@ async def test_create_file_set_smb_properties(self, **kwargs): file_client = await self._get_file_client(storage_account_name, storage_account_key) 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) + file_creation_time = file_last_write_time = file_change_time = datetime( + 2022, 3, 10, 10, 14, 30, 500000, tzinfo=timezone.utc + ) # Act await file_client.create_file( @@ -705,7 +727,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 @@ -713,8 +736,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 @@ -770,7 +793,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): @@ -794,7 +818,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 @@ -819,7 +844,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): @@ -849,7 +875,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): @@ -870,9 +896,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 @@ -906,14 +930,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() @@ -926,17 +946,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 @@ -946,7 +965,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 @@ -958,9 +977,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) @@ -973,7 +990,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 @@ -997,14 +1014,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 @@ -1042,11 +1060,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) @@ -1068,9 +1087,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 @@ -1078,7 +1098,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() @@ -1096,11 +1117,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() @@ -1133,7 +1154,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 @@ -1159,7 +1181,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) @@ -1184,7 +1207,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): @@ -1215,7 +1239,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 @@ -1225,10 +1249,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 @@ -1241,12 +1265,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) @@ -1256,10 +1281,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 @@ -1269,7 +1294,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 @@ -1283,10 +1308,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) @@ -1295,11 +1320,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) @@ -1308,10 +1333,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 @@ -1344,7 +1369,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) @@ -1366,9 +1392,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 @@ -1390,7 +1417,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): @@ -1408,7 +1436,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 @@ -1429,13 +1457,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 @@ -1456,13 +1485,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() @@ -1471,7 +1501,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 @@ -1481,10 +1511,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) @@ -1505,7 +1535,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 @@ -1521,7 +1551,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 @@ -1539,7 +1569,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 @@ -1553,11 +1583,15 @@ 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_client = await self._create_file(storage_account_name, storage_account_key, file_name=source_file_name) + source_file_name = "testfile1" + source_file_client = await self._create_file( + storage_account_name, storage_account_key, file_name=source_file_name + ) - destination_file_name = 'filetoupdate' - destination_file_client = await self._create_file(storage_account_name, storage_account_key, file_name=destination_file_name) + destination_file_name = "filetoupdate" + destination_file_client = await self._create_file( + storage_account_name, storage_account_key, file_name=destination_file_name + ) # generate SAS for the source file sas_token_for_source_file = self.generate_sas( @@ -1567,10 +1601,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): @@ -1584,13 +1618,17 @@ 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_client = await self._create_file(storage_account_name, storage_account_key, file_name=source_file_name) - data = b'abcdefghijklmnop' * 32 + source_file_name = "testfile" + source_file_client = await self._create_file( + storage_account_name, storage_account_key, file_name=source_file_name + ) + data = b"abcdefghijklmnop" * 32 await source_file_client.upload_range(data, offset=0, length=512) - destination_file_name = 'filetoupdate' - destination_file_client = await self._create_empty_file(storage_account_name, storage_account_key, file_name=destination_file_name) + destination_file_name = "filetoupdate" + destination_file_client = await self._create_empty_file( + storage_account_name, storage_account_key, file_name=destination_file_name + ) # generate SAS for the source file sas_token_for_source_file = self.generate_sas( @@ -1600,9 +1638,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) @@ -1612,8 +1651,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() @@ -1624,18 +1663,23 @@ 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") + access_token = await self.get_credential(ShareServiceClient, is_async=True).get_token( + "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 @@ -1644,14 +1688,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_client = await self._create_file(storage_account_name, storage_account_key, file_name=source_file_name) - data = b'abcdefghijklmnop' * 32 + source_file_name = "testfile" + source_file_client = await self._create_file( + storage_account_name, storage_account_key, file_name=source_file_name + ) + data = b"abcdefghijklmnop" * 32 await source_file_client.upload_range(data, offset=0, length=512) - destination_file_name = 'filetoupdate' - destination_file_client = await self._create_empty_file(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') + destination_file_name = "filetoupdate" + destination_file_client = await self._create_empty_file( + 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") # generate SAS for the source file sas_token_for_source_file = self.generate_sas( @@ -1661,14 +1709,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 @@ -1676,8 +1726,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() @@ -1687,15 +1737,19 @@ 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) - data = b'abcdefghijklmnop' * 65536 - await source_file_client.upload_range(data, offset=0, length=end+1) + source_file_client = await self._create_empty_file( + 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) - 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) + 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 + ) # generate SAS for the source file sas_token_for_source_file = self.generate_sas( @@ -1705,12 +1759,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 @@ -1718,8 +1773,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() @@ -1729,14 +1784,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 @@ -1747,13 +1801,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 @@ -1766,14 +1822,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 @@ -1784,13 +1839,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 @@ -1811,7 +1868,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() @@ -1826,9 +1883,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 @@ -1838,9 +1896,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 @@ -1852,10 +1910,10 @@ async def test_update_file_unicode(self, **kwargs): file_client = await self._create_file(storage_account_name, storage_account_key) # Act - data = u'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() @@ -1878,7 +1936,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 @@ -1900,9 +1959,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 @@ -1912,7 +1972,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 @@ -1927,13 +1987,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() @@ -1955,7 +2016,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) @@ -1967,7 +2029,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 @@ -1975,20 +2037,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 @@ -2005,7 +2067,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) @@ -2017,7 +2080,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 @@ -2025,20 +2088,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 @@ -2052,9 +2115,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) @@ -2066,7 +2130,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 @@ -2075,22 +2139,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 @@ -2105,7 +2169,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) @@ -2116,21 +2181,23 @@ 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): await file_client.get_ranges_diff(previous_sharesnapshot=previous_snapshot) 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) + ranges, cleared = await file_client.get_ranges_diff( + 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 @@ -2145,10 +2212,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) @@ -2158,10 +2226,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 @@ -2176,9 +2244,10 @@ 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) snapshot = await share_client.create_snapshot() snapshot_client = ShareFileClient( @@ -2186,7 +2255,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() @@ -2212,7 +2282,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) @@ -2223,7 +2294,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() @@ -2247,12 +2319,13 @@ 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) - + share_client = self.fsc.get_share_client(self.share_name) snapshot = await share_client.create_snapshot() snapshot_client = ShareFileClient( @@ -2260,7 +2333,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() @@ -2270,10 +2344,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 @@ -2286,16 +2360,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() @@ -2313,17 +2388,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() @@ -2341,19 +2417,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 @@ -2366,10 +2444,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): @@ -2379,8 +2458,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() @@ -2397,8 +2476,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) @@ -2411,8 +2491,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() @@ -2429,8 +2509,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) @@ -2452,15 +2533,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() @@ -2478,23 +2559,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() @@ -2508,18 +2587,24 @@ async def test_copy_file_async_private_file_async(self, **kwargs): secondary_storage_account_name = kwargs.pop("secondary_storage_account_name") secondary_storage_account_key = kwargs.pop("secondary_storage_account_key") - self._setup(storage_account_name, storage_account_key, secondary_storage_account_name, secondary_storage_account_key.secret) + self._setup( + storage_account_name, + storage_account_key, + secondary_storage_account_name, + 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) @@ -2535,8 +2620,13 @@ async def test_copy_file_async_private_file_with_sas_async(self, **kwargs): secondary_storage_account_name = kwargs.pop("secondary_storage_account_name") secondary_storage_account_key = kwargs.pop("secondary_storage_account_key") - self._setup(storage_account_name, storage_account_key, secondary_storage_account_name, secondary_storage_account_key.secret) - data = b'12345678' * 1024 + self._setup( + storage_account_name, + storage_account_key, + secondary_storage_account_name, + secondary_storage_account_key.secret, + ) + data = b"12345678" * 1024 await self._create_remote_share() source_file = await self._create_remote_file(file_data=data) sas_token = self.generate_sas( @@ -2548,21 +2638,22 @@ 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'] - await self._wait_for_async_copy(self.share_name, target_file_name) + 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() actual_data = await content.readall() @@ -2576,8 +2667,13 @@ async def test_abort_copy_file_async(self, **kwargs): secondary_storage_account_name = kwargs.pop("secondary_storage_account_name") secondary_storage_account_key = kwargs.pop("secondary_storage_account_key") - 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 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) @@ -2590,24 +2686,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() @@ -2618,8 +2715,13 @@ async def test_abort_copy_file_async_with_oauth(self, **kwargs): secondary_storage_account_key = kwargs.pop("secondary_storage_account_key") token_credential = self.get_credential(ShareServiceClient, is_async=True) - 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 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) @@ -2632,25 +2734,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 @@ -2662,19 +2765,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 @@ -2683,21 +2787,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 @@ -2706,31 +2811,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 @@ -2745,10 +2851,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 = u'hello world啊齄丂狛狜'.encode('utf-8') + data = "hello world啊齄丂狛狜".encode("utf-8") await file_client.upload_file(data) # Assert @@ -2766,7 +2873,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 = u'hello world啊齄丂狛狜'.encode('utf-8') + data = "hello world啊齄丂狛狜".encode("utf-8") await file_client.upload_file(data, file_attributes=NTFSAttributes(temporary=True)) # Assert @@ -2774,7 +2881,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 @@ -2783,7 +2890,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+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==' + 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) @@ -2792,7 +2899,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 @@ -2817,13 +2925,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)) @@ -2848,13 +2958,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:]) @@ -2876,16 +2987,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() @@ -2902,7 +3014,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: @@ -2910,8 +3023,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) @@ -2931,13 +3044,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)) @@ -2946,8 +3061,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) @@ -2968,7 +3083,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) @@ -2977,8 +3093,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]) @@ -2998,7 +3114,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) @@ -3026,13 +3143,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)) @@ -3061,7 +3180,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 @@ -3088,13 +3208,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)) @@ -3117,7 +3239,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): @@ -3128,14 +3250,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 @@ -3146,14 +3269,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 = u'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) @@ -3170,17 +3294,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 = u'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) @@ -3196,13 +3321,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) @@ -3226,7 +3352,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) @@ -3248,7 +3375,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) @@ -3270,9 +3398,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 @@ -3297,9 +3426,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 @@ -3332,7 +3462,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() @@ -3344,19 +3475,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( @@ -3365,12 +3496,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() @@ -3402,7 +3532,8 @@ 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) @@ -3432,7 +3563,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() @@ -3445,7 +3577,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) @@ -3455,7 +3586,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() @@ -3471,7 +3603,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() @@ -3496,7 +3629,8 @@ 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) + credential=token, + ) response = requests.get(file_client.url) # Assert @@ -3519,11 +3653,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 @@ -3531,16 +3665,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) + 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() @@ -3549,7 +3684,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, @@ -3564,17 +3699,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) + 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() @@ -3597,7 +3733,8 @@ 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) @@ -3614,13 +3751,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 @@ -3634,20 +3771,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): @@ -3658,15 +3795,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 @@ -3680,9 +3817,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) @@ -3691,7 +3828,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 @@ -3706,11 +3843,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() @@ -3727,14 +3864,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() @@ -3748,7 +3885,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) @@ -3757,16 +3894,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), 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 @@ -3778,13 +3916,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() @@ -3799,20 +3935,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 @@ -3832,19 +3966,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 @@ -3862,7 +3996,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) @@ -3877,7 +4011,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 @@ -3898,7 +4032,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) @@ -3913,7 +4047,7 @@ async def test_bad_audience_file_client(self, **kwargs): file_path=file_name, credential=token_credential, token_intent=TEST_INTENT, - audience=f'https://badaudience.file.core.windows.net' + audience=f"https://badaudience.file.core.windows.net", ) # Assert @@ -3928,18 +4062,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() @@ -3947,28 +4083,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 @@ -3977,8 +4107,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 @@ -3986,17 +4115,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() @@ -4015,7 +4142,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() @@ -4046,7 +4173,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!" @@ -4067,23 +4194,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" @@ -4105,11 +4225,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\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) @@ -4133,8 +4253,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\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) @@ -4156,7 +4276,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" @@ -4179,7 +4300,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) 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 df8a607f27f8..b452a7e91d3b 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 @@ -18,15 +19,15 @@ # ------------------------------------------------------------------------------ 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): @@ -41,14 +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 + ) # --Direct Parameters Test Cases -------------------------------------------- @FileSharePreparer() @@ -61,12 +73,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): @@ -78,8 +94,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 @@ -98,8 +118,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 @@ -109,20 +134,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): @@ -130,15 +157,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): @@ -151,9 +179,16 @@ def test_create_service_empty_key(self, **kwargs): # Passing an empty key to create account should fail. with pytest.raises(ValueError) as e: service_type( - self.account_url(storage_account_name, "file"), share_name='foo', directory_path='bar', file_path='baz') + self.account_url(storage_account_name, "file"), + 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): @@ -165,11 +200,20 @@ def test_create_service_with_socket_timeout(self, **kwargs): for service_type in SERVICES.items(): # Act 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') + self.account_url(storage_account_name, "file"), + credential=self.account_key.secret, + 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') + self.account_url(storage_account_name, "file"), + credential=self.account_key.secret, + connection_timeout=22, + share_name="foo", + directory_path="bar", + file_path="baz", + ) # Assert self.validate_standard_account_endpoints(service, service_type[1]) @@ -184,16 +228,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): @@ -201,12 +246,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 @@ -220,22 +266,28 @@ def test_create_service_with_connection_string_endpoint_protocol(self, **kwargs) storage_account_key = kwargs.pop("storage_account_key") 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) + conn_string = ( + "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.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() def test_create_service_with_connection_string_emulated(self, **kwargs): @@ -244,12 +296,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): @@ -258,15 +311,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): @@ -275,22 +330,25 @@ 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): @@ -300,52 +358,60 @@ def test_create_service_with_custom_account_endpoint_path(self, **kwargs): 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") + service = ShareDirectoryClient( + 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.url.startswith('http://local-machine:11002/custom/account/path/foo/bar%2Fbaz?sharesnapshot=snap&') + 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&" + ) - 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") + service = ShareFileClient( + 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" @@ -353,8 +419,10 @@ def test_create_service_with_custom_account_endpoint_path(self, **kwargs): 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.url.startswith('http://local-machine:11002/custom/account/path/foo/bar/baz/file?sharesnapshot=snap&') + 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&" + ) service = ShareFileClient(account_url=custom_account_url, share_name="foo", file_path="file") assert service.account_name == None @@ -364,23 +432,25 @@ 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?") - @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") + @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 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): @@ -404,8 +474,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) @@ -418,23 +488,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") @@ -448,13 +521,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): @@ -467,11 +541,13 @@ def test_error_with_malformed_conn_str(self, **kwargs): for service_type in SERVICES.items(): # Act with pytest.raises(ValueError) as e: - 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", ";"): + 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", ";"): 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() @@ -484,11 +560,16 @@ def test_closing_pipeline_client(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 with service: - assert hasattr(service, 'close') + assert hasattr(service, "close") service.close() @FileSharePreparer() @@ -501,6 +582,10 @@ def test_closing_pipeline_client_simple(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", + ) 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 bd2dac98405b..096570af3eb1 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 @@ -18,15 +18,15 @@ # ------------------------------------------------------------------------------ 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): @@ -42,14 +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 + ) # --Direct Parameters Test Cases -------------------------------------------- @FileSharePreparer() @@ -62,12 +73,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): @@ -79,8 +94,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 @@ -98,8 +117,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 @@ -109,20 +133,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): @@ -130,15 +156,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): @@ -151,9 +178,16 @@ async def test_create_service_empty_key(self, **kwargs): # Passing an empty key to create account should fail. with pytest.raises(ValueError) as e: service_type( - self.account_url(storage_account_name, "file"), share_name='foo', directory_path='bar', file_path='baz') + self.account_url(storage_account_name, "file"), + 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): @@ -165,11 +199,20 @@ async def test_create_service_with_socket_timeout(self, **kwargs): for service_type in SERVICES.items(): # Act 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') + self.account_url(storage_account_name, "file"), + credential=self.account_key.secret, + 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') + self.account_url(storage_account_name, "file"), + credential=self.account_key.secret, + connection_timeout=22, + share_name="foo", + directory_path="bar", + file_path="baz", + ) # Assert self.validate_standard_account_endpoints(service, service_type[1]) @@ -184,16 +227,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): @@ -201,12 +245,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 @@ -220,21 +265,28 @@ async def test_create_service_with_connection_string_endpoint_protocol(self, **k storage_account_key = kwargs.pop("storage_account_key") 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) + conn_string = ( + "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') + service = service_type[0].from_connection_string( + 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.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): @@ -243,11 +295,13 @@ 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') + service_type[0].from_connection_string( + conn_string, share_name="foo", directory_path="bar", file_path="baz" + ) @FileSharePreparer() async def test_create_service_with_connection_string_fails_if_secondary_without_primary(self, **kwargs): @@ -256,15 +310,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): @@ -273,22 +329,25 @@ 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): @@ -298,52 +357,60 @@ async def test_create_service_with_custom_account_endpoint_path(self, **kwargs): 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") + service = ShareDirectoryClient( + 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.url.startswith('http://local-machine:11002/custom/account/path/foo/bar%2Fbaz?sharesnapshot=snap&') + 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&" + ) - 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") + service = ShareFileClient( + 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" @@ -351,8 +418,10 @@ async def test_create_service_with_custom_account_endpoint_path(self, **kwargs): 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.url.startswith('http://local-machine:11002/custom/account/path/foo/bar/baz/file?sharesnapshot=snap&') + 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&" + ) service = ShareFileClient(account_url=custom_account_url, share_name="foo", file_path="file") assert service.account_name == None @@ -362,8 +431,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 @@ -375,8 +444,8 @@ async 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"] await service.get_service_properties(raw_response_hook=callback) @@ -389,23 +458,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") @@ -419,13 +491,14 @@ async 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"] - 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): @@ -437,11 +510,16 @@ async def test_closing_pipeline_client(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 async with service: - assert hasattr(service, 'close') + assert hasattr(service, "close") await service.close() @FileSharePreparer() @@ -454,7 +532,10 @@ async def test_closing_pipeline_client_simple(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", + ) 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 5681e5181e52..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 @@ -15,7 +15,7 @@ ShareServiceClient, ShareSmbSettings, SmbEncryptionInTransit, - SmbMultichannel + SmbMultichannel, ) from devtools_testutils import recorded_by_proxy @@ -37,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: @@ -80,29 +81,25 @@ 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())) @@ -112,15 +109,12 @@ def test_file_service_properties(self, **kwargs): 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() @@ -137,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 @@ -146,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 @@ -163,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"] @@ -175,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] @@ -184,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() @@ -195,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 @@ -208,13 +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) + 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 ef369db70060..0c525ec1b276 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 @@ -16,7 +16,7 @@ ShareProtocolSettings, ShareSmbSettings, SmbEncryptionInTransit, - SmbMultichannel + SmbMultichannel, ) from azure.storage.fileshare.aio import ShareServiceClient @@ -40,6 +40,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(TypeError): ShareProtocolSettings(smb=ShareSmbSettings(multichannel=SmbMultichannel())) @@ -115,15 +113,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() @@ -140,7 +135,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 @@ -149,15 +144,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 @@ -166,10 +162,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"] @@ -178,7 +174,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] @@ -187,7 +184,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() @@ -199,7 +196,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 59362970ae2a..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,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 @@ -19,7 +20,7 @@ from test_helpers import ProgressTracker # ------------------------------------------------------------------------------ -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) @@ -73,7 +76,7 @@ def write(self, data): def read(self, count): return self.wrapped_file.read(count) - + def seekable(self): return False @@ -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 = u'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,17 +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+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==' + 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 @@ -136,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 @@ -166,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() @@ -189,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)) @@ -206,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 @@ -222,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)) @@ -239,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 @@ -257,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)) @@ -275,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 @@ -292,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() @@ -320,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 = [] @@ -352,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: @@ -378,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)) @@ -410,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)) @@ -444,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)) @@ -482,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: @@ -519,29 +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) @@ -562,29 +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) @@ -604,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 @@ -616,22 +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) @@ -651,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 @@ -664,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() @@ -678,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 @@ -701,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 @@ -732,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)) @@ -750,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 @@ -775,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: @@ -799,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: @@ -828,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 @@ -852,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) @@ -860,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 @@ -887,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 @@ -913,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 @@ -955,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 @@ -992,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 @@ -1023,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 = u'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 @@ -1048,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 = u'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 @@ -1088,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: @@ -1115,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: @@ -1140,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: @@ -1178,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: @@ -1210,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)) @@ -1228,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() @@ -1248,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)) @@ -1266,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() @@ -1284,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) @@ -1307,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) @@ -1318,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 @@ -1333,19 +1366,19 @@ 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) - + # Assert assert file_content.properties.server_encrypted @@ -1355,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() @@ -1383,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)) @@ -1409,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) @@ -1438,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) @@ -1467,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 @@ -1481,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) @@ -1492,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 f60f2a3eb683..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,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 @@ -20,7 +21,7 @@ from test_helpers_async import ProgressTracker # ------------------------------------------------------------------------------ -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) @@ -74,7 +76,7 @@ def write(self, data): def read(self, count): return self.wrapped_file.read(count) - + def seekable(self): return False @@ -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 = u'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,17 +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+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==' + 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 @@ -142,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) @@ -175,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) @@ -200,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)) @@ -218,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 @@ -235,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)) @@ -253,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 @@ -272,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)) @@ -291,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 @@ -308,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() @@ -337,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: @@ -367,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 = [] @@ -400,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)) @@ -435,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)) @@ -472,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)) @@ -513,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: @@ -553,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)) @@ -599,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)) @@ -644,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 @@ -656,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)) @@ -694,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() @@ -725,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 @@ -751,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) @@ -786,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)) @@ -803,18 +826,18 @@ 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 - self.assert_download_progress(end_range - start_range + 1, self.MAX_CHUNK_GET_SIZE, self.MAX_SINGLE_GET_SIZE, progress) + 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 + ) @FileSharePreparer() @recorded_by_proxy_async @@ -827,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: @@ -854,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: @@ -886,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 @@ -910,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 @@ -919,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 @@ -948,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 @@ -976,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 @@ -1020,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 @@ -1059,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 @@ -1092,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 = u'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 @@ -1119,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 = u'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 @@ -1161,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: @@ -1191,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: @@ -1219,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: @@ -1260,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: @@ -1295,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)) @@ -1314,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() @@ -1335,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)) @@ -1354,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() @@ -1373,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) @@ -1397,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) @@ -1409,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 @@ -1424,20 +1448,20 @@ 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) - + # Assert assert file_content.properties.server_encrypted @@ -1447,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() @@ -1477,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)) @@ -1504,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) @@ -1534,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) @@ -1564,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 @@ -1578,14 +1606,10 @@ 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) # Assert progress.assert_complete() assert length == read - 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 20f957a55390..e16110c792b4 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_handle.py +++ b/sdk/storage/azure-storage-file-share/tests/test_handle.py @@ -13,7 +13,7 @@ from settings.testcase import FileSharePreparer # ------------------------------------------------------------------------------ -TEST_SHARE_NAME = 'test-share' +TEST_SHARE_NAME = "test-share" # ------------------------------------------------------------------------------ @@ -50,7 +50,7 @@ def test_list_handles_on_share(self, **kwargs): # don't run live, since the test set up was highly manual # only run when recording, or playing back in CI - + self._setup(storage_account_name, storage_account_key) share = self.fsc.get_share_client(TEST_SHARE_NAME) root = share.get_directory_client() @@ -107,10 +107,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 @@ -130,7 +129,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)) @@ -156,7 +155,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()) @@ -182,13 +181,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() @@ -210,8 +209,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() @@ -224,19 +223,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 b6f00fa9f6ef..14eec54586b9 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 @@ -13,7 +13,7 @@ from settings.testcase import FileSharePreparer # ------------------------------------------------------------------------------ -TEST_SHARE_NAME = 'test-share' +TEST_SHARE_NAME = "test-share" # ------------------------------------------------------------------------------ @@ -61,13 +61,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() @@ -91,8 +91,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() @@ -105,9 +105,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 = [] @@ -116,10 +116,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 6f36069ec952..532d17c83bbc 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_helpers.py +++ b/sdk/storage/azure-storage-file-share/tests/test_helpers.py @@ -33,11 +33,7 @@ def assert_complete(self): class MockHttpClientResponse(Response): def __init__( - self, url: str, - body_bytes: bytes, - headers: Dict[str, Any], - status: int = 200, - reason: str = "OK" + self, url: str, body_bytes: bytes, headers: Dict[str, Any], status: int = 200, reason: str = "OK" ) -> None: super(MockHttpClientResponse).__init__() self._url = url @@ -57,8 +53,9 @@ class MockStorageTransport(HttpTransport): This transport returns legacy http response objects from azure core and is intended only to test our backwards compatibility support. """ + def send(self, request: HttpRequest, **kwargs: Any) -> RequestsTransportResponse: - if request.method == 'GET': + if request.method == "GET": # download_file headers = { "Content-Type": "application/octet-stream", @@ -75,9 +72,9 @@ def send(self, request: HttpRequest, **kwargs: Any) -> RequestsTransportResponse request.url, b"Hello World!", headers, - ) + ), ) - elif request.method == 'HEAD': + elif request.method == "HEAD": # get_file_properties rest_response = RequestsTransportResponse( request=request, @@ -88,9 +85,9 @@ def send(self, request: HttpRequest, **kwargs: Any) -> RequestsTransportResponse "Content-Type": "application/octet-stream", "Content-Length": "1024", }, - ) + ), ) - elif request.method == 'PUT': + elif request.method == "PUT": # upload_file rest_response = RequestsTransportResponse( request=request, @@ -101,10 +98,10 @@ def send(self, request: HttpRequest, **kwargs: Any) -> RequestsTransportResponse "Content-Length": "0", }, 201, - "Created" - ) + "Created", + ), ) - elif request.method == 'DELETE': + elif request.method == "DELETE": # delete_file rest_response = RequestsTransportResponse( request=request, @@ -115,8 +112,8 @@ def send(self, request: HttpRequest, **kwargs: Any) -> RequestsTransportResponse "Content-Length": "0", }, 202, - "Accepted" - ) + "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 0a7da86e53aa..b5cd7413a1aa 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 @@ -55,11 +55,7 @@ async def read(self, size: int = -1) -> bytes: class MockAioHttpClientResponse(ClientResponse): def __init__( - self, url: str, - body_bytes: bytes, - headers: Dict[str, Any], - status: int = 200, - reason: str = "OK" + self, url: str, body_bytes: bytes, headers: Dict[str, Any], status: int = 200, reason: str = "OK" ) -> None: super(MockAioHttpClientResponse).__init__() self._url = url @@ -77,11 +73,12 @@ def __init__( class MockStorageTransport(AsyncHttpTransport): """ - This transport returns legacy http response objects from azure core and is + This transport returns legacy http response objects from azure core and is intended only to test our backwards compatibility support. """ + async def send(self, request: HttpRequest, **kwargs: Any) -> AioHttpTransportResponse: - if request.method == 'GET': + if request.method == "GET": # download_file headers = { "Content-Type": "application/octet-stream", @@ -99,9 +96,9 @@ async def send(self, request: HttpRequest, **kwargs: Any) -> AioHttpTransportRes b"Hello Async World!", headers, ), - decompress=False + decompress=False, ) - elif request.method == 'HEAD': + elif request.method == "HEAD": # get_file_properties rest_response = AioHttpTransportResponse( request=request, @@ -113,9 +110,9 @@ async def send(self, request: HttpRequest, **kwargs: Any) -> AioHttpTransportRes "Content-Length": "1024", }, ), - decompress=False + decompress=False, ) - elif request.method == 'PUT': + elif request.method == "PUT": # upload_file rest_response = AioHttpTransportResponse( request=request, @@ -126,11 +123,11 @@ async def send(self, request: HttpRequest, **kwargs: Any) -> AioHttpTransportRes "Content-Length": "0", }, 201, - "Created" + "Created", ), - decompress=False + decompress=False, ) - elif request.method == 'DELETE': + elif request.method == "DELETE": # delete_file rest_response = AioHttpTransportResponse( request=request, @@ -141,9 +138,9 @@ async def send(self, request: HttpRequest, **kwargs: Any) -> AioHttpTransportRes "Content-Length": "0", }, 202, - "Accepted" + "Accepted", ), - decompress=False + decompress=False, ) else: raise ValueError("The request is not accepted as part of MockStorageTransport.") 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 3b714c7d465d..be0067dcb8c6 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_nfs.py +++ b/sdk/storage/azure-storage-file-share/tests/test_nfs.py @@ -11,7 +11,7 @@ ClientAuthenticationError, HttpResponseError, ResourceExistsError, - ResourceNotFoundError + ResourceNotFoundError, ) from azure.storage.fileshare import ( ContentSettings, @@ -19,16 +19,16 @@ DirectoryProperties, ShareFileClient, ShareDirectoryClient, - ShareServiceClient + 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): @@ -36,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 @@ -65,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 @@ -85,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() @@ -96,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 @@ -128,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 @@ -158,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) @@ -176,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() @@ -192,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) @@ -204,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() @@ -230,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 @@ -264,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 @@ -284,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 @@ -326,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 52b17b157346..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 @@ -11,14 +11,9 @@ ClientAuthenticationError, HttpResponseError, ResourceExistsError, - ResourceNotFoundError -) -from azure.storage.fileshare import ( - ContentSettings, - DirectoryProperties, - FileProperties, - ShareServiceClient + 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 @@ -27,9 +22,9 @@ 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 TestStorageFileNFSAsync(AsyncStorageRecordedTestCase): @@ -37,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 @@ -63,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: @@ -77,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 @@ -97,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() @@ -108,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 @@ -140,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 @@ -170,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) @@ -188,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() @@ -204,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) @@ -216,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() @@ -242,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 @@ -276,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 @@ -296,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 @@ -338,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 3b6572837a68..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,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 @@ -15,7 +16,7 @@ ClientAuthenticationError, HttpResponseError, ResourceExistsError, - ResourceNotFoundError + ResourceNotFoundError, ) from azure.core.pipeline.transport import RequestsTransport from azure.storage.fileshare import ( @@ -35,7 +36,7 @@ ShareRootSquash, ShareSasPermissions, ShareServiceClient, - StorageErrorCode + StorageErrorCode, ) from devtools_testutils import recorded_by_proxy @@ -43,10 +44,11 @@ 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") @@ -60,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) @@ -78,7 +81,7 @@ def _create_share(self, prefix=TEST_SHARE_PREFIX, **kwargs): 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): try: @@ -88,11 +91,16 @@ def _delete_shares(self, prefix=TEST_SHARE_PREFIX): # --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"}) + 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"}, + ) 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") + share_client = ShareClient.from_share_url( + "http://127.0.0.1:11002/account/share?snapshot=baz&", credential="credential" + ) assert share_client.share_name == "share" assert share_client.snapshot == "baz" @@ -128,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() @@ -146,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() @@ -171,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) @@ -221,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 @@ -244,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): @@ -257,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 @@ -275,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 @@ -298,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 @@ -316,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) @@ -332,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 @@ -348,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() @@ -371,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) @@ -389,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 @@ -407,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) @@ -419,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 @@ -430,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 @@ -475,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) @@ -493,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): @@ -557,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() @@ -605,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() @@ -711,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) @@ -728,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 = u'啊齄丂狛狜' + share_name = "啊齄丂狛狜" # Act with pytest.raises(HttpResponseError): @@ -764,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() @@ -811,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() @@ -831,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() @@ -842,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() @@ -854,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() @@ -868,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 @@ -885,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)) @@ -905,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) @@ -928,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 @@ -996,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 @@ -1016,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) @@ -1033,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() @@ -1052,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() @@ -1138,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() @@ -1237,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() @@ -1308,7 +1315,7 @@ def test_set_share_acl_with_empty_signed_identifiers(self, **kwargs): # 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() @@ -1316,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() @@ -1324,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, @@ -1337,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 @@ -1356,12 +1363,15 @@ 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() @FileSharePreparer() @@ -1373,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 @@ -1387,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() @@ -1400,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) @@ -1419,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() @@ -1431,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() @@ -1445,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() @@ -1457,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() @@ -1491,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 @@ -1518,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) @@ -1537,7 +1546,7 @@ 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, ) @@ -1557,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 @@ -1580,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 @@ -1632,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()) @@ -1662,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 @@ -1676,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 @@ -1711,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 @@ -1722,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 @@ -1762,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 @@ -1798,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() @@ -1815,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() @@ -1845,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()) @@ -1873,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) @@ -1911,9 +1911,7 @@ def test_share_cross_tenant_sas(self, **kwargs): 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) @@ -1922,9 +1920,7 @@ def test_share_cross_tenant_sas(self, **kwargs): 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 @@ -1946,16 +1942,14 @@ def test_share_cross_tenant_sas(self, **kwargs): 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 @@ -1969,20 +1963,19 @@ def test_share_cross_tenant_sas(self, **kwargs): 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 5face0374f45..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,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 @@ -14,7 +15,7 @@ ClientAuthenticationError, HttpResponseError, ResourceExistsError, - ResourceNotFoundError + ResourceNotFoundError, ) from azure.core.pipeline.transport import AioHttpTransport from azure.storage.fileshare import ( @@ -30,7 +31,7 @@ ShareRootSquash, ShareSasPermissions, ShareServiceClient, - StorageErrorCode + StorageErrorCode, ) from azure.storage.fileshare.aio import ShareClient, ShareFileClient, ShareServiceClient @@ -38,8 +39,9 @@ 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" # ------------------------------------------------------------------------------ @@ -64,6 +66,7 @@ async def _delete_shares(self, prefix=TEST_SHARE_PREFIX): await self.fsc.delete_share(l.name, delete_snapshots=True) except: pass + # --Helpers----------------------------------------------------------------- def _get_share_reference(self, prefix=TEST_SHARE_PREFIX): share_name = self.get_resource_name(prefix) @@ -112,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() @@ -130,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): @@ -156,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) @@ -209,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 @@ -232,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): @@ -245,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 @@ -263,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 @@ -286,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 @@ -304,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) @@ -320,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 @@ -336,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() @@ -359,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) @@ -378,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) @@ -397,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) @@ -409,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 @@ -420,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 @@ -465,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) @@ -483,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): @@ -550,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() @@ -598,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() @@ -704,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) @@ -721,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 = u'啊齄丂狛狜' + share_name = "啊齄丂狛狜" # Act with pytest.raises(HttpResponseError): @@ -759,7 +759,9 @@ async def test_list_shares_enable_snapshot_virtual_directory_access(self, **kwar 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 = await self._create_share(protocols="NFS", headers={'x-ms-enable-snapshot-virtual-directory-access': "False"}) + share = await self._create_share( + protocols="NFS", headers={"x-ms-enable-snapshot-virtual-directory-access": "False"} + ) # Act list_props = [] @@ -768,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() @@ -810,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) @@ -819,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() @@ -832,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() @@ -846,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() @@ -857,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() @@ -871,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 @@ -888,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 = [] @@ -910,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) @@ -935,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)) @@ -948,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) @@ -1009,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 @@ -1023,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): @@ -1032,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) @@ -1050,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() @@ -1069,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() @@ -1259,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() @@ -1330,7 +1332,7 @@ async def test_set_share_acl_with_empty_signed_identifiers(self, **kwargs): # 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() @@ -1338,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() @@ -1346,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, @@ -1359,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 @@ -1378,12 +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() @@ -1395,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 @@ -1411,9 +1416,9 @@ 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') + self.assertNamedItemInContainer(resp, "dir1") + self.assertNamedItemInContainer(resp, "dir2") + self.assertNamedItemInContainer(resp, "file1") await self._delete_shares(share) @FileSharePreparer() @@ -1424,16 +1429,15 @@ async def test_list_directories_and_files_with_snapshot(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_name = await self._create_share() - dir1 = share_name.get_directory_client('dir1') + dir1 = share_name.get_directory_client("dir1") await dir1.create_directory() - dir2 = share_name.get_directory_client('dir2') + dir2 = share_name.get_directory_client("dir2") await dir2.create_directory() snapshot1 = await share_name.create_snapshot() - dir3 = share_name.get_directory_client('dir3') + dir3 = share_name.get_directory_client("dir3") await dir3.create_directory() - file1 = share_name.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_name.share_name, snapshot=snapshot1) @@ -1445,8 +1449,8 @@ 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') + self.assertNamedItemInContainer(resp, "dir1") + self.assertNamedItemInContainer(resp, "dir2") await self._delete_shares(share_name) @FileSharePreparer() @@ -1457,12 +1461,12 @@ async def test_list_directories_and_files_with_num_results(self, **kwargs): self._setup(storage_account_name, storage_account_key) share_name = await self._create_share() - dir1 = await share_name.create_directory('dir1') + 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') + 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_name.list_directories_and_files(results_per_page=2).by_page() @@ -1473,8 +1477,8 @@ 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') + self.assertNamedItemInContainer(results, "dir1") + self.assertNamedItemInContainer(results, "filea1") await self._delete_shares(share_name) @FileSharePreparer() @@ -1485,22 +1489,22 @@ async def test_list_directories_and_files_with_num_results_and_marker(self, **kw self._setup(storage_account_name, storage_account_key) share_name = await self._create_share() - dir1 = share_name.get_directory_client('dir1') + 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_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 = [] async for r in await generator1.__anext__(): result1.append(r) - 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 = [] async for r in await generator2.__anext__(): result2.append(r) @@ -1508,10 +1512,10 @@ 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_name) @@ -1523,26 +1527,26 @@ 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') + self.assertNamedItemInContainer(resp, "pref_file2") + self.assertNamedItemInContainer(resp, "pref_dir3") await self._delete_shares(share) @pytest.mark.live_test_only @@ -1552,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) @@ -1570,7 +1574,7 @@ 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, ) @@ -1589,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 @@ -1613,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 @@ -1666,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 = [] @@ -1676,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 = [] @@ -1700,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 @@ -1714,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 @@ -1744,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(): @@ -1757,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(): @@ -1799,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 @@ -1835,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() @@ -1852,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() @@ -1882,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(): @@ -1912,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) @@ -1950,9 +1947,7 @@ async def test_share_cross_tenant_sas(self, **kwargs): 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) @@ -1961,9 +1956,7 @@ async def test_share_cross_tenant_sas(self, **kwargs): 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 @@ -1985,16 +1978,14 @@ async def test_share_cross_tenant_sas(self, **kwargs): 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(): @@ -2010,16 +2001,14 @@ async def test_share_cross_tenant_sas(self, **kwargs): 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..7cb450202a52 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/tsp-location.yaml @@ -0,0 +1,4 @@ +directory: specification/storage/data-plane/FileStorage +commit: b760190f490001759361c8e7b59d8b5b191dc12d +repo: Azure/azure-rest-api-specs +additionalDirectories: [] From bdc0650ebddb4730f98018e82d21071f2c259d9d Mon Sep 17 00:00:00 2001 From: antisch Date: Mon, 23 Mar 2026 15:59:08 +1300 Subject: [PATCH 02/45] Refactor --- .../storage/fileshare/_client_helpers.py | 29 +++++ .../storage/fileshare/_directory_client.py | 54 +++++++-- .../azure/storage/fileshare/_file_client.py | 103 +++++++++++++++--- .../_generated/operations/_operations.py | 4 +- .../fileshare/_generated/operations/_patch.py | 103 ++++++++++++++++++ .../azure/storage/fileshare/_lease.py | 26 ++++- .../azure/storage/fileshare/_share_client.py | 50 ++++++--- .../fileshare/_share_service_client.py | 25 +++-- .../storage/fileshare/_shared/base_client.py | 92 +--------------- .../fileshare/_shared/base_client_async.py | 2 - .../storage/fileshare/_shared/policies.py | 28 ----- .../fileshare/aio/_directory_client_async.py | 52 +++++++-- .../fileshare/aio/_file_client_async.py | 102 ++++++++++++++--- .../storage/fileshare/aio/_lease_async.py | 26 ++++- .../fileshare/aio/_share_client_async.py | 49 ++++++--- .../aio/_share_service_client_async.py | 22 ++-- 16 files changed, 545 insertions(+), 222 deletions(-) create mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py new file mode 100644 index 000000000000..3172c2d75368 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py @@ -0,0 +1,29 @@ +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +"""Helpers for the Azure File Share convenience layer clients.""" + + +class _NoOpCredential: + """No-op credential for the generated client when auth is handled by the convenience layer pipeline.""" + + def get_token(self, *args, **kwargs): + raise RuntimeError("This credential should not be used to get tokens directly.") + + +def _strip_snapshot_from_url(url): + """Strip sharesnapshot and snapshot query params from URL. + + The generated client should receive a base URL without snapshot params, + since snapshots are passed per-operation. + """ + if "?" not in url: + return url + base, qs = url.split("?", 1) + filtered = "&".join( + part for part in qs.split("&") if not part.startswith("sharesnapshot=") and not part.startswith("snapshot=") + ) + return f"{base}?{filtered}" if filtered else base 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 dcb565cfafbc..b6ad8f4c15d4 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 @@ -25,7 +25,7 @@ from ._parser import _datetime_to_str, _get_file_permission, _parse_snapshot 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.base_client import _NoOpCredential, _patch_generated_client +from ._client_helpers import _NoOpCredential, _strip_snapshot_from_url from ._shared.request_handlers import add_metadata_headers from ._shared.response_handlers import process_storage_error, return_response_headers @@ -130,16 +130,11 @@ def __init__( self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( - url=self._base_url, + url=_strip_snapshot_from_url(self.url), credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) - self._client._config.allow_trailing_dot = self.allow_trailing_dot - self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot - self._client._config.file_request_intent = self.file_request_intent - self._client._config.sharesnapshot = self.snapshot - _patch_generated_client(self._client) def __enter__(self) -> Self: self._client.__enter__() @@ -419,6 +414,8 @@ def create_directory(self, **kwargs: Any) -> Dict[str, Any]: timeout=timeout, cls=return_response_headers, headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ), ) @@ -449,7 +446,12 @@ def delete_directory(self, **kwargs: Any) -> 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) @@ -557,6 +559,9 @@ def rename_directory(self, new_name: str, **kwargs: Any) -> "ShareDirectoryClien replace_if_exists=overwrite, destination_lease_id=destination_access_conditions, headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) @@ -612,6 +617,8 @@ def list_directories_and_files( self._client.directory.list_files_and_directories_segment, sharesnapshot=self.snapshot, timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) return ItemPaged( @@ -644,6 +651,8 @@ def list_handles(self, recursive: bool = False, **kwargs: Any) -> ItemPaged[Hand sharesnapshot=self.snapshot, timeout=timeout, recursive=recursive, + 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) @@ -679,6 +688,8 @@ def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[str, i recursive=None, sharesnapshot=self.snapshot, cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) return { @@ -723,6 +734,8 @@ def close_all_handles(self, recursive: bool = False, **kwargs: Any) -> Dict[str, recursive=recursive, sharesnapshot=self.snapshot, cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) except HttpResponseError as error: @@ -754,7 +767,14 @@ def get_directory_properties(self, **kwargs: Any) -> "DirectoryProperties": try: response = cast( "DirectoryProperties", - self._client.directory.get_properties(timeout=timeout, cls=deserialize_directory_properties, **kwargs), + 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) @@ -787,7 +807,12 @@ def set_directory_metadata(self, metadata: Dict[str, Any], **kwargs: Any) -> Dic return cast( Dict[str, Any], self._client.directory.set_metadata( - timeout=timeout, cls=return_response_headers, headers=headers, **kwargs + 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: @@ -808,7 +833,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: @@ -889,6 +919,8 @@ def set_http_headers( 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, ), ) 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 ef4fb6b75460..7fea6b4e6e8c 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 @@ -38,7 +38,7 @@ get_source_access_conditions, ) from ._shared.base_client import StorageAccountHostsMixin, parse_connection_str, parse_query -from ._shared.base_client import _NoOpCredential, _patch_generated_client +from ._client_helpers import _NoOpCredential, _strip_snapshot_from_url from ._shared.constants import DEFAULT_MAX_CONCURRENCY from ._shared.request_handlers import add_metadata_headers, get_length from ._shared.response_handlers import return_response_headers, process_storage_error @@ -48,7 +48,6 @@ from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential, TokenCredential from ._models import ContentSettings, NTFSAttributes from ._shared.base_client import StorageConfiguration -from ._shared.base_client import _NoOpCredential, _patch_generated_client def _upload_file_helper( @@ -194,16 +193,11 @@ def __init__( self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( - url=self._base_url, + url=_strip_snapshot_from_url(self.url), credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) - self._client._config.allow_trailing_dot = self.allow_trailing_dot - self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot - self._client._config.file_request_intent = self.file_request_intent - self._client._config.sharesnapshot = self.snapshot - _patch_generated_client(self._client) def __enter__(self) -> Self: self._client.__enter__() @@ -371,7 +365,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: @@ -505,6 +504,8 @@ def create_file( headers=headers, timeout=timeout, cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ), ) @@ -821,6 +822,9 @@ def start_copy_from_url(self, source_url: str, **kwargs: Any) -> Dict[str, Any]: 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, ), ) @@ -861,7 +865,14 @@ def abort_copy(self, copy_id: Union[str, FileProperties], **kwargs: Any) -> None elif isinstance(copy_id, Dict): copy_id = copy_id["copy_id"] try: - self._client.file.abort_copy(copyid=copy_id, lease_id=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) @@ -932,6 +943,12 @@ def download_file( 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, config=self._config, @@ -942,6 +959,8 @@ def download_file( share=self.share_name, lease_id=access_conditions, cls=deserialize_file_stream, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) @@ -977,7 +996,13 @@ def delete_file(self, **kwargs: Any) -> None: access_conditions = get_access_conditions(kwargs.pop("lease", None)) timeout = kwargs.pop("timeout", None) try: - self._client.file.delete(lease_id=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) @@ -1101,6 +1126,9 @@ def rename_file(self, new_name: str, **kwargs: Any) -> "ShareFileClient": source_lease_id=source_access_conditions, destination_lease_id=dest_access_conditions, headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) @@ -1139,6 +1167,8 @@ def get_file_properties(self, **kwargs: Any) -> FileProperties: 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, ), ) @@ -1249,6 +1279,8 @@ def set_http_headers( 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, ), ) @@ -1296,6 +1328,8 @@ def set_file_metadata(self, metadata: Optional[Dict[str, Any]] = None, **kwargs: headers=headers, metadata=metadata, lease_id=access_conditions, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ), ) @@ -1372,6 +1406,8 @@ def upload_range(self, data: bytes, offset: int, length: int, **kwargs: Any) -> 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, ), ) @@ -1452,6 +1488,9 @@ def upload_range_from_url( options = _upload_range_from_url_options( 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: @@ -1486,6 +1525,9 @@ def get_ranges( :rtype: List[dict[str, int]] """ 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 + options["sharesnapshot"] = self.snapshot try: ranges = self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1543,6 +1585,9 @@ def get_ranges_diff( support_rename=include_renames, **kwargs, ) + options["allow_trailing_dot"] = self.allow_trailing_dot + options["file_request_intent"] = self.file_request_intent + options["sharesnapshot"] = self.snapshot try: ranges = self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1596,6 +1641,8 @@ def clear_range(self, offset: int, length: int, **kwargs: Any) -> Dict[str, Any] 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, ), ) @@ -1638,6 +1685,8 @@ def resize_file(self, size: int, **kwargs: Any) -> Dict[str, Any]: 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, ), ) @@ -1660,7 +1709,12 @@ def list_handles(self, **kwargs: Any) -> ItemPaged[Handle]: 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 + self._client.file.list_handles, + sharesnapshot=self.snapshot, + timeout=timeout, + 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) @@ -1690,7 +1744,13 @@ def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[str, i raise ValueError("Handle ID '*' is not supported. Use 'close_all_handles' instead.") try: response = self._client.file.force_close_handles( - handle_id=handle_id, marker=None, sharesnapshot=self.snapshot, cls=return_response_headers, **kwargs + handle_id=handle_id, + marker=None, + sharesnapshot=self.snapshot, + cls=return_response_headers, + 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), @@ -1730,6 +1790,8 @@ def close_all_handles(self, **kwargs: Any) -> Dict[str, int]: marker=continuation_token, sharesnapshot=self.snapshot, cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) except HttpResponseError as error: @@ -1774,7 +1836,12 @@ def create_hardlink( return cast( Dict[str, Any], self._client.file.create_hard_link( - target_file=target, lease_id=lease, timeout=timeout, cls=return_response_headers, **kwargs + target_file=target, + lease_id=lease, + timeout=timeout, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs, ), ) except HttpResponseError as error: @@ -1832,6 +1899,7 @@ def create_symlink( lease_id=lease, timeout=timeout, cls=return_response_headers, + file_request_intent=self.file_request_intent, **kwargs, ), ) @@ -1854,7 +1922,12 @@ def get_symlink(self, *, timeout: Optional[int] = None, **kwargs: Any) -> Dict[s try: return cast( Dict[str, Any], - self._client.file.get_symbolic_link(timeout=timeout, cls=return_response_headers, **kwargs), + 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/_generated/operations/_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_operations.py index b09857c988be..1dd2dfe37d04 100644 --- 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 @@ -1351,7 +1351,7 @@ def build_file_download_request( # Construct headers _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") if range is not None: - _headers["Range"] = _SERIALIZER.header("range", range, "str") + _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" @@ -1848,7 +1848,7 @@ def build_file_get_range_list_request( # Construct headers _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") if range is not None: - _headers["Range"] = _SERIALIZER.header("range", range, "str") + _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: 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 87676c65a8f0..8029044b14be 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 @@ -7,11 +7,107 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +import functools + +from . import _operations __all__: list[str] = [] # Add all objects you want publicly available to users at this package level +# --------------------------------------------------------------------------- +# Emitter bug fixes applied via patch_sdk() +# +# 1. Trailing slash: The emitter generates _url = "/" for @route("") which +# creates a trailing slash when combined with the base URL. Fix: change +# _url from "/" to "" in the affected build_*_request functions. +# +# 2. Missing Accept header: Operations using StorageOperationNoBody (no +# response body) don't get an Accept header generated, even though error +# responses are XML. Fix: set Accept: application/xml as the default. +# --------------------------------------------------------------------------- + +# Build functions that generate _url = "/" (trailing slash bug) +_TRAILING_SLASH_FUNCTIONS = [ + "build_file_create_request", + "build_file_download_request", + "build_file_get_properties_request", + "build_file_delete_request", + "build_file_start_copy_request", +] + +# Build functions missing Accept header +_MISSING_ACCEPT_FUNCTIONS = [ + "build_service_set_properties_request", + "build_share_create_request", + "build_share_get_properties_request", + "build_share_delete_request", + "build_share_acquire_lease_request", + "build_share_release_lease_request", + "build_share_change_lease_request", + "build_share_renew_lease_request", + "build_share_break_lease_request", + "build_share_create_snapshot_request", + "build_share_create_permission_request", + "build_share_set_properties_request", + "build_share_set_metadata_request", + "build_share_set_access_policy_request", + "build_share_restore_request", + "build_directory_create_request", + "build_directory_get_properties_request", + "build_directory_delete_request", + "build_directory_set_properties_request", + "build_directory_set_metadata_request", + "build_directory_force_close_handles_request", + "build_directory_rename_request", + "build_file_create_request", + "build_file_get_properties_request", + "build_file_delete_request", + "build_file_set_http_headers_request", + "build_file_set_metadata_request", + "build_file_acquire_lease_request", + "build_file_release_lease_request", + "build_file_change_lease_request", + "build_file_break_lease_request", + "build_file_upload_range_request", + "build_file_upload_range_from_url_request", + "build_file_start_copy_request", + "build_file_abort_copy_request", + "build_file_force_close_handles_request", + "build_file_rename_request", + "build_file_create_symbolic_link_request", + "build_file_get_symbolic_link_request", + "build_file_create_hard_link_request", +] + + +def _fix_trailing_slash(build_fn): + """Wrap a build_*_request function to strip the trailing slash from _url = "/".""" + + @functools.wraps(build_fn) + def wrapper(*args, **kwargs): + request = build_fn(*args, **kwargs) + url = request.url + if url == "/" or url.startswith("/?"): + request.url = url[1:] # Strip leading "/" + return request + + return wrapper + + +def _fix_accept_header(build_fn): + """Wrap a build_*_request function to add Accept: application/xml if missing.""" + + @functools.wraps(build_fn) + def wrapper(*args, **kwargs): + request = build_fn(*args, **kwargs) + if "Accept" not in request.headers: + request.headers["Accept"] = "application/xml" + return request + + return wrapper + + def patch_sdk(): """Do not remove from this file. @@ -19,3 +115,10 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ + for fn_name in _TRAILING_SLASH_FUNCTIONS: + original = getattr(_operations, fn_name) + setattr(_operations, fn_name, _fix_trailing_slash(original)) + + for fn_name in _MISSING_ACCEPT_FUNCTIONS: + original = getattr(_operations, fn_name) + setattr(_operations, fn_name, _fix_accept_header(original)) 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 918c4f27751d..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 @@ -49,12 +49,15 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self.id = lease_id or str(uuid.uuid4()) self.last_modified = None self.etag = None + 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 + 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.") @@ -93,10 +96,13 @@ def acquire(self, **kwargs: Any) -> None: lease_duration = kwargs.pop("lease_duration", -1) if 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), lease_duration=lease_duration, proposed_lease_id=self.id, + file_request_intent=self._file_request_intent, cls=return_response_headers, **kwargs ) @@ -133,6 +139,7 @@ def renew(self, **kwargs: Any) -> None: lease_id=self.id, timeout=kwargs.pop("timeout", None), sharesnapshot=self._snapshot, + file_request_intent=self._file_request_intent, cls=return_response_headers, **kwargs ) @@ -159,8 +166,14 @@ def release(self, **kwargs: Any) -> None: try: if 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), cls=return_response_headers, **kwargs + lease_id=self.id, + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, + cls=return_response_headers, + **kwargs ) except HttpResponseError as error: process_storage_error(error) @@ -187,10 +200,13 @@ def change(self, proposed_lease_id: str, **kwargs: Any) -> None: try: if 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), + file_request_intent=self._file_request_intent, cls=return_response_headers, **kwargs ) @@ -241,8 +257,14 @@ def break_lease(self, **kwargs: Any) -> int: 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), cls=return_response_headers, **kwargs + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, + cls=return_response_headers, + **kwargs ) except HttpResponseError as error: process_storage_error(error) 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 f0e10d4c01a7..ce73bee1fef6 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 @@ -24,7 +24,7 @@ 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 ._shared.base_client import parse_connection_str, parse_query, StorageAccountHostsMixin, TransportWrapper -from ._shared.base_client import _NoOpCredential, _patch_generated_client +from ._client_helpers import _NoOpCredential, _strip_snapshot_from_url 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 @@ -118,16 +118,11 @@ def __init__( self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( - url=self._base_url, + url=_strip_snapshot_from_url(self.url), credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) - self._client._config.allow_trailing_dot = self.allow_trailing_dot - self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot - self._client._config.file_request_intent = self.file_request_intent - self._client._config.sharesnapshot = self.snapshot - _patch_generated_client(self._client) def __enter__(self) -> Self: self._client.__enter__() @@ -424,6 +419,7 @@ def create_share(self, **kwargs: Any) -> Dict[str, Any]: share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, cls=return_response_headers, headers=headers, + file_request_intent=self.file_request_intent, **kwargs ), ) @@ -471,7 +467,11 @@ def create_snapshot(self, **kwargs: Any) -> Dict[str, Any]: return cast( Dict[str, Any], self._client.share.create_snapshot( - timeout=timeout, cls=return_response_headers, headers=headers, **kwargs + timeout=timeout, + cls=return_response_headers, + headers=headers, + file_request_intent=self.file_request_intent, + **kwargs ), ) except HttpResponseError as error: @@ -530,6 +530,7 @@ def delete_share( sharesnapshot=self.snapshot, lease_id=access_conditions, delete_snapshots=delete_include, + file_request_intent=self.file_request_intent, **kwargs ) except HttpResponseError as error: @@ -577,6 +578,7 @@ def get_share_properties(self, **kwargs: Any) -> "ShareProperties": sharesnapshot=self.snapshot, cls=deserialize_share_properties, lease_id=access_conditions, + file_request_intent=self.file_request_intent, **kwargs ), ) @@ -630,6 +632,7 @@ def set_share_quota(self, quota: int, **kwargs: Any) -> Dict[str, Any]: access_tier=None, lease_id=access_conditions, cls=return_response_headers, + file_request_intent=self.file_request_intent, **kwargs ), ) @@ -704,6 +707,7 @@ def set_share_properties(self, **kwargs: Any) -> Dict[str, Any]: 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 ), ) @@ -755,7 +759,12 @@ def set_share_metadata(self, metadata: Dict[str, str], **kwargs: Any) -> Dict[st return cast( Dict[str, Any], self._client.share.set_metadata( - timeout=timeout, cls=return_response_headers, headers=headers, lease_id=access_conditions, **kwargs + timeout=timeout, + cls=return_response_headers, + headers=headers, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs ), ) except HttpResponseError as error: @@ -787,7 +796,11 @@ def get_share_access_policy(self, **kwargs: Any) -> Dict[str, Any]: timeout = kwargs.pop("timeout", None) try: response, identifiers = self._client.share.get_access_policy( - timeout=timeout, cls=return_headers_and_deserialized, lease_id=access_conditions, **kwargs + timeout=timeout, + cls=return_headers_and_deserialized, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs ) except HttpResponseError as error: process_storage_error(error) @@ -848,6 +861,7 @@ def set_share_access_policy(self, signed_identifiers: Dict[str, "AccessPolicy"], timeout=timeout, cls=return_response_headers, lease_id=access_conditions, + file_request_intent=self.file_request_intent, **kwargs ), ) @@ -882,7 +896,10 @@ def get_share_stats(self, **kwargs: Any) -> int: timeout = kwargs.pop("timeout", None) try: stats = cast( - ShareStats, self._client.share.get_statistics(timeout=timeout, lease_id=access_conditions, **kwargs) + 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: @@ -972,7 +989,10 @@ def create_permission_for_share(self, file_permission: str, **kwargs: Any) -> Op 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) @@ -1001,7 +1021,11 @@ def get_permission_for_share(self, permission_key: str, **kwargs: Any) -> str: return cast( str, self._client.share.get_permission( - file_permission_key=permission_key, cls=deserialize_permission, timeout=timeout, **kwargs + file_permission_key=permission_key, + cls=deserialize_permission, + timeout=timeout, + file_request_intent=self.file_request_intent, + **kwargs ), ) except HttpResponseError as error: 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 7a046d71cf25..e802345fd0a0 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 @@ -26,7 +26,7 @@ from ._share_client import ShareClient from ._share_service_client_helpers import _parse_url from ._shared.base_client import StorageAccountHostsMixin, TransportWrapper, parse_connection_str, parse_query -from ._shared.base_client import _NoOpCredential, _patch_generated_client +from ._client_helpers import _NoOpCredential, _strip_snapshot_from_url from ._shared.parser import _to_utc_datetime from ._shared.response_handlers import parse_to_internal_user_delegation_key, process_storage_error @@ -127,15 +127,11 @@ def __init__( self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( - url=self._base_url, + url=_strip_snapshot_from_url(self.url), credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) - self._client._config.allow_trailing_dot = self.allow_trailing_dot - self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot - self._client._config.file_request_intent = self.file_request_intent - _patch_generated_client(self._client) def __enter__(self) -> Self: self._client.__enter__() @@ -275,7 +271,9 @@ def get_service_properties(self, **kwargs: Any) -> Dict[str, Any]: """ 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) @@ -334,7 +332,12 @@ def set_service_properties( 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) @@ -390,7 +393,11 @@ def list_shares( results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( - self._client.service.list_shares_segment, include=include, timeout=timeout, **kwargs + self._client.service.list_shares_segment, + include=include, + timeout=timeout, + file_request_intent=self.file_request_intent, + **kwargs, ) return ItemPaged( command, 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 364519178643..3f7609b9f026 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 @@ -3,7 +3,6 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -import functools import logging import uuid from typing import ( @@ -56,7 +55,6 @@ StorageLoggingPolicy, StorageRequestHook, StorageResponseHook, - StorageTrailingSlashPolicy, ) from .request_handlers import serialize_batch_body, _get_batch_request_delimiter from .response_handlers import PartialBatchErrorException, process_storage_error @@ -77,75 +75,6 @@ } -class _NoOpCredential: - """No-op credential for the generated client when auth is handled by the convenience layer pipeline.""" - - def get_token(self, *args, **kwargs): - raise RuntimeError("This credential should not be used to get tokens directly.") - - -def _patch_generated_client(client): - """Apply workarounds to the generated client after construction. - - Wraps operation group methods to inject per-operation params from config. - """ - # Wrap operation group methods to inject per-operation params from config - # (allow_trailing_dot, allow_source_trailing_dot, file_request_intent, sharesnapshot) - # These were config-level in AutoRest but are per-operation in TypeSpec. - # For operations that accept sharesnapshot as a parameter, it's injected via kwargs. - # For operations that DON'T (e.g. download), it's injected via raw_request_hook. - import inspect - from urllib.parse import quote as _url_quote - - _per_op_params = ("allow_trailing_dot", "allow_source_trailing_dot", "file_request_intent", "sharesnapshot") - for group_name in ["service", "share", "directory", "file"]: - group = getattr(client, group_name) - for name in list(vars(type(group))): - if name.startswith("_"): - continue - method = getattr(group, name) - if not callable(method): - continue - - sig_params = set(inspect.signature(method).parameters.keys()) - inject = [p for p in _per_op_params if p in sig_params] - has_snapshot_param = "sharesnapshot" in sig_params - - # Skip methods that need no injection at all - if not inject and has_snapshot_param: - continue - if not inject and not has_snapshot_param: - # Only needs snapshot URL injection - pass - - def _make_wrapper(original, config, inject_params, _needs_snapshot_hook): - @functools.wraps(original) - def wrapper(*args, **kwargs): - for p in inject_params: - kwargs.setdefault(p, getattr(config, p, None)) - # For operations without sharesnapshot param, inject via URL hook - if _needs_snapshot_hook: - snapshot = getattr(config, "sharesnapshot", None) - if snapshot: - existing_hook = kwargs.get("raw_request_hook") - - def _snapshot_hook(request, _orig=existing_hook, _snap=snapshot): - url = request.http_request.url - if "sharesnapshot=" not in url: - sep = "&" if "?" in url else "?" - request.http_request.url = f'{url}{sep}sharesnapshot={_url_quote(_snap, safe="")}' - if _orig: - _orig(request) - - kwargs["raw_request_hook"] = _snapshot_hook - return original(*args, **kwargs) - - return wrapper - - needs_snapshot_hook = not has_snapshot_param - setattr(group, name, _make_wrapper(method, client._config, inject, needs_snapshot_hook)) - - class StorageAccountHostsMixin(object): _client: Any @@ -218,24 +147,6 @@ def url(self) -> str: """ return self._format_url(self._hosts[self._location_mode]) # type: ignore - @property - def _base_url(self) -> str: - """The endpoint URL without snapshot query parameters (for the generated client base URL). - - SAS credentials are preserved in the URL because the generated client's - operations include them in every request. Only ``sharesnapshot`` and - ``snapshot`` params are stripped — they are injected per-operation via - ``_patch_generated_client`` or by ``_InjectSnapshotPolicy``. - """ - full_url = self.url - if "?" not in full_url: - return full_url - base, qs = full_url.split("?", 1) - filtered = "&".join( - part for part in qs.split("&") if not part.startswith("sharesnapshot=") and not part.startswith("snapshot=") - ) - return f"{base}?{filtered}" if filtered else base - @property def primary_endpoint(self) -> str: """The full primary endpoint URL. @@ -297,7 +208,7 @@ def location_mode(self) -> str: def location_mode(self, value): if self._hosts.get(value): self._location_mode = value - self._client._config.url = self._base_url # pylint: disable=protected-access + self._client._config.url = self.url # pylint: disable=protected-access else: raise ValueError(f"No host URL for location mode: {value}") @@ -369,7 +280,6 @@ def _create_pipeline( transport = RequestsTransport(**kwargs) policies = [ QueueMessagePolicy(), - StorageTrailingSlashPolicy(), config.proxy_policy, config.user_agent_policy, StorageContentValidation(), 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 c564639d87bf..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 @@ -40,7 +40,6 @@ StorageHeadersPolicy, StorageHosts, StorageRequestHook, - StorageTrailingSlashPolicy, ) from .policies_async import AsyncStorageBearerTokenCredentialPolicy, AsyncStorageResponseHook from .response_handlers import PartialBatchErrorException, process_storage_error @@ -129,7 +128,6 @@ def _create_pipeline( hosts = self._hosts policies = [ QueueMessagePolicy(), - StorageTrailingSlashPolicy(), config.proxy_policy, config.user_agent_policy, StorageContentValidation(), 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 f76e656b649a..abb8c8ff9e7d 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 @@ -126,30 +126,6 @@ def on_request(self, request): request.http_request.url = urljoin(request.http_request.url, message_id) -class StorageTrailingSlashPolicy(SansIOHTTPPolicy): - """Normalizes request URLs and headers for compatibility with test recordings. - - The TypeSpec-generated operations produce paths like ``/`` which, when - combined with the base URL, create a trailing slash that does not match - test-proxy recordings made with the old generated code. Also renames - the ``Range`` header to ``x-ms-range`` to match old recordings. - """ - - def on_request(self, request): - url = request.http_request.url - parsed = urlparse(url) - path = parsed.path - if len(path) > 1 and path.endswith("/"): - cleaned = parsed._replace(path=path.rstrip("/")) - request.http_request.url = urlunparse(cleaned) - - # The TypeSpec emitter uses the standard Range header, but the old - # generated code used x-ms-range. Rename for recording compatibility. - headers = request.http_request.headers - if "Range" in headers and "x-ms-range" not in headers: - headers["x-ms-range"] = headers.pop("Range") - - class StorageHeadersPolicy(HeadersPolicy): request_id_header_name = "x-ms-client-request-id" @@ -158,10 +134,6 @@ def on_request(self, request: "PipelineRequest") -> None: current_time = format_date_time(time()) request.http_request.headers["x-ms-date"] = current_time - # Ensure Accept header defaults to application/xml for Storage APIs - if "Accept" not in request.http_request.headers: - request.http_request.headers["Accept"] = "application/xml" - custom_id = request.context.options.pop("client_request_id", None) request.http_request.headers["x-ms-client-request-id"] = custom_id or str(uuid.uuid1()) 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 d2b36ac24da6..20200954f3f1 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 @@ -26,7 +26,7 @@ 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 -from .._shared.base_client import _NoOpCredential, _patch_generated_client +from .._client_helpers import _NoOpCredential, _strip_snapshot_from_url from .._shared.policies_async import ExponentialRetry from .._shared.request_handlers import add_metadata_headers from .._shared.response_handlers import process_storage_error, return_response_headers @@ -139,16 +139,11 @@ def __init__( self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( - url=self._base_url, + url=_strip_snapshot_from_url(self.url), credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) - self._client._config.allow_trailing_dot = self.allow_trailing_dot - self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot - self._client._config.file_request_intent = self.file_request_intent - self._client._config.sharesnapshot = self.snapshot - _patch_generated_client(self._client) async def __aenter__(self) -> Self: await self._client.__aenter__() @@ -429,6 +424,8 @@ async def create_directory(self, **kwargs: Any) -> Dict[str, Any]: timeout=timeout, cls=return_response_headers, headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ), ) @@ -459,7 +456,12 @@ async def delete_directory(self, **kwargs: Any) -> 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) @@ -567,6 +569,9 @@ async def rename_directory(self, new_name: str, **kwargs: Any) -> "ShareDirector replace_if_exists=overwrite, destination_lease_id=destination_access_conditions, headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) @@ -622,6 +627,8 @@ def list_directories_and_files( self._client.directory.list_files_and_directories_segment, sharesnapshot=self.snapshot, timeout=timeout, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) return AsyncItemPaged( @@ -654,6 +661,8 @@ def list_handles(self, recursive: bool = False, **kwargs: Any) -> AsyncItemPaged sharesnapshot=self.snapshot, timeout=timeout, recursive=recursive, + 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) @@ -673,7 +682,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: @@ -711,6 +725,8 @@ async def close_handle(self, handle: Union[str, "Handle"], **kwargs: Any) -> Dic recursive=None, sharesnapshot=self.snapshot, cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) return { @@ -755,6 +771,8 @@ async def close_all_handles(self, recursive: bool = False, **kwargs: Any) -> Dic recursive=recursive, sharesnapshot=self.snapshot, cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) except HttpResponseError as error: @@ -787,7 +805,12 @@ async def get_directory_properties(self, **kwargs: Any) -> "DirectoryProperties" response = cast( "DirectoryProperties", await self._client.directory.get_properties( - timeout=timeout, cls=deserialize_directory_properties, **kwargs + 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: @@ -821,7 +844,12 @@ async def set_directory_metadata(self, metadata: Dict[str, Any], **kwargs: Any) return cast( Dict[str, Any], await self._client.directory.set_metadata( - timeout=timeout, cls=return_response_headers, headers=headers, **kwargs + 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: @@ -900,6 +928,8 @@ async def set_http_headers( 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, ), ) 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 93e2c6b8e58f..07f15fd7f030 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 @@ -55,7 +55,7 @@ ) from .._shared.base_client import StorageAccountHostsMixin, parse_query from .._shared.base_client_async import AsyncStorageAccountHostsMixin, parse_connection_str -from .._shared.base_client import _NoOpCredential, _patch_generated_client +from .._client_helpers import _NoOpCredential, _strip_snapshot_from_url from .._shared.constants import DEFAULT_MAX_CONCURRENCY from .._shared.policies_async import ExponentialRetry from .._shared.request_handlers import add_metadata_headers, get_length @@ -219,16 +219,11 @@ def __init__( self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( - url=self._base_url, + url=_strip_snapshot_from_url(self.url), credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) - self._client._config.allow_trailing_dot = self.allow_trailing_dot - self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot - self._client._config.file_request_intent = self.file_request_intent - self._client._config.sharesnapshot = self.snapshot - _patch_generated_client(self._client) async def __aenter__(self) -> Self: await self._client.__aenter__() @@ -387,7 +382,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: @@ -519,6 +519,8 @@ async def create_file( headers=headers, timeout=timeout, cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ), ) @@ -835,6 +837,9 @@ async def start_copy_from_url(self, source_url: str, **kwargs: Any) -> Dict[str, 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, ), ) @@ -874,7 +879,14 @@ async def abort_copy(self, copy_id: Union[str, FileProperties], **kwargs: Any) - elif isinstance(copy_id, Dict): copy_id = copy_id["copy_id"] try: - await self._client.file.abort_copy(copyid=copy_id, lease_id=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) @@ -948,6 +960,12 @@ async def download_file( 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, config=self._config, @@ -958,6 +976,8 @@ async def download_file( share=self.share_name, lease_id=access_conditions, cls=deserialize_file_stream, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) await downloader._setup() # pylint: disable=protected-access @@ -995,7 +1015,13 @@ async def delete_file(self, **kwargs: Any) -> None: access_conditions = get_access_conditions(kwargs.pop("lease", None)) timeout = kwargs.pop("timeout", None) try: - await self._client.file.delete(lease_id=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) @@ -1119,6 +1145,9 @@ async def rename_file(self, new_name: str, **kwargs: Any) -> "ShareFileClient": source_lease_id=source_access_conditions, destination_lease_id=dest_access_conditions, headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + allow_source_trailing_dot=self.allow_source_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) @@ -1157,6 +1186,8 @@ async def get_file_properties(self, **kwargs: Any) -> FileProperties: 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, ), ) @@ -1265,6 +1296,8 @@ async def set_http_headers( 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, ), ) @@ -1312,6 +1345,8 @@ async def set_file_metadata(self, metadata: Optional[Dict[str, Any]] = None, **k timeout=timeout, cls=return_response_headers, headers=headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ), ) @@ -1387,6 +1422,8 @@ async def upload_range(self, data: bytes, offset: int, length: int, **kwargs: An 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, ), ) @@ -1467,6 +1504,9 @@ async def upload_range_from_url( options = _upload_range_from_url_options( 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: @@ -1501,6 +1541,9 @@ async def get_ranges( :rtype: List[dict[str, int]] """ 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 + options["sharesnapshot"] = self.snapshot try: ranges = await self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1558,6 +1601,9 @@ async def get_ranges_diff( support_rename=include_renames, **kwargs, ) + options["allow_trailing_dot"] = self.allow_trailing_dot + options["file_request_intent"] = self.file_request_intent + options["sharesnapshot"] = self.snapshot try: ranges = await self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1611,6 +1657,8 @@ async def clear_range(self, offset: int, length: int, **kwargs: Any) -> Dict[str 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, ), ) @@ -1653,6 +1701,8 @@ async def resize_file(self, size: int, **kwargs: Any) -> Dict[str, Any]: 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, ), ) @@ -1675,7 +1725,12 @@ def list_handles(self, **kwargs: Any) -> AsyncItemPaged[Handle]: 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 + self._client.file.list_handles, + sharesnapshot=self.snapshot, + timeout=timeout, + 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) @@ -1705,7 +1760,13 @@ async def close_handle(self, handle: Union[str, Handle], **kwargs: Any) -> Dict[ 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, marker=None, sharesnapshot=self.snapshot, cls=return_response_headers, **kwargs + handle_id=handle_id, + marker=None, + sharesnapshot=self.snapshot, + cls=return_response_headers, + 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), @@ -1746,6 +1807,8 @@ async def close_all_handles(self, **kwargs: Any) -> Dict[str, int]: marker=continuation_token, sharesnapshot=self.snapshot, cls=return_response_headers, + allow_trailing_dot=self.allow_trailing_dot, + file_request_intent=self.file_request_intent, **kwargs, ) except HttpResponseError as error: @@ -1790,7 +1853,12 @@ async def create_hardlink( return cast( Dict[str, Any], await self._client.file.create_hard_link( - target_file=target, lease_id=lease, timeout=timeout, cls=return_response_headers, **kwargs + target_file=target, + lease_id=lease, + timeout=timeout, + cls=return_response_headers, + file_request_intent=self.file_request_intent, + **kwargs, ), ) except HttpResponseError as error: @@ -1848,6 +1916,7 @@ async def create_symlink( lease_id=lease, timeout=timeout, cls=return_response_headers, + file_request_intent=self.file_request_intent, **kwargs, ), ) @@ -1870,7 +1939,12 @@ async def get_symlink(self, *, timeout: Optional[int] = None, **kwargs: Any) -> try: return cast( Dict[str, Any], - await self._client.file.get_symbolic_link(timeout=timeout, cls=return_response_headers, **kwargs), + 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 0697b433db8a..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 @@ -59,12 +59,15 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential self.id = lease_id or str(uuid.uuid4()) self.last_modified = None self.etag = None + 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 + 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.") @@ -103,10 +106,13 @@ async def acquire(self, **kwargs: Any) -> None: lease_duration = kwargs.pop("lease_duration", -1) if 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), lease_duration=lease_duration, proposed_lease_id=self.id, + file_request_intent=self._file_request_intent, cls=return_response_headers, **kwargs ) @@ -143,6 +149,7 @@ async def renew(self, **kwargs: Any) -> None: lease_id=self.id, timeout=kwargs.pop("timeout", None), sharesnapshot=self._snapshot, + file_request_intent=self._file_request_intent, cls=return_response_headers, **kwargs ) @@ -169,8 +176,14 @@ async def release(self, **kwargs: Any) -> None: try: if 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), cls=return_response_headers, **kwargs + lease_id=self.id, + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, + cls=return_response_headers, + **kwargs ) except HttpResponseError as error: process_storage_error(error) @@ -197,10 +210,13 @@ async def change(self, proposed_lease_id: str, **kwargs: Any) -> None: try: if 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), + file_request_intent=self._file_request_intent, cls=return_response_headers, **kwargs ) @@ -251,8 +267,14 @@ async def break_lease(self, **kwargs: Any) -> int: 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), cls=return_response_headers, **kwargs + timeout=kwargs.pop("timeout", None), + file_request_intent=self._file_request_intent, + cls=return_response_headers, + **kwargs ) except HttpResponseError as error: process_storage_error(error) 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 326d2df49918..1e8f410e4f61 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 @@ -25,7 +25,7 @@ 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.base_client import _NoOpCredential, _patch_generated_client +from .._client_helpers import _NoOpCredential, _strip_snapshot_from_url 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 .._serialize import get_access_conditions, get_api_version @@ -127,16 +127,11 @@ def __init__( self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( - url=self._base_url, + url=_strip_snapshot_from_url(self.url), credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) - self._client._config.allow_trailing_dot = self.allow_trailing_dot - self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot - self._client._config.file_request_intent = self.file_request_intent - self._client._config.sharesnapshot = self.snapshot - _patch_generated_client(self._client) async def __aenter__(self) -> Self: await self._client.__aenter__() @@ -424,6 +419,7 @@ async def create_share(self, **kwargs: Any) -> Dict[str, Any]: share_provisioned_bandwidth_mibps=share_provisioned_bandwidth_mibps, cls=return_response_headers, headers=headers, + file_request_intent=self.file_request_intent, **kwargs ), ) @@ -471,7 +467,11 @@ async def create_snapshot(self, **kwargs: Any) -> Dict[str, Any]: return cast( Dict[str, Any], await self._client.share.create_snapshot( - timeout=timeout, cls=return_response_headers, headers=headers, **kwargs + timeout=timeout, + cls=return_response_headers, + headers=headers, + file_request_intent=self.file_request_intent, + **kwargs ), ) except HttpResponseError as error: @@ -529,6 +529,7 @@ async def delete_share( sharesnapshot=self.snapshot, delete_snapshots=delete_include, lease_id=access_conditions, + file_request_intent=self.file_request_intent, **kwargs ) except HttpResponseError as error: @@ -576,6 +577,7 @@ async def get_share_properties(self, **kwargs: Any) -> "ShareProperties": sharesnapshot=self.snapshot, cls=deserialize_share_properties, lease_id=access_conditions, + file_request_intent=self.file_request_intent, **kwargs ), ) @@ -629,6 +631,7 @@ async def set_share_quota(self, quota: int, **kwargs: Any) -> Dict[str, Any]: access_tier=None, cls=return_response_headers, lease_id=access_conditions, + file_request_intent=self.file_request_intent, **kwargs ), ) @@ -703,6 +706,7 @@ async def set_share_properties(self, **kwargs: Any) -> Dict[str, Any]: 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 ), ) @@ -754,7 +758,12 @@ async def set_share_metadata(self, metadata: Dict[str, str], **kwargs: Any) -> D return cast( Dict[str, Any], await self._client.share.set_metadata( - timeout=timeout, cls=return_response_headers, headers=headers, lease_id=access_conditions, **kwargs + timeout=timeout, + cls=return_response_headers, + headers=headers, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs ), ) except HttpResponseError as error: @@ -786,7 +795,11 @@ async def get_share_access_policy(self, **kwargs: Any) -> Dict[str, Any]: timeout = kwargs.pop("timeout", None) try: response, identifiers = await self._client.share.get_access_policy( - timeout=timeout, cls=return_headers_and_deserialized, lease_id=access_conditions, **kwargs + timeout=timeout, + cls=return_headers_and_deserialized, + lease_id=access_conditions, + file_request_intent=self.file_request_intent, + **kwargs ) except HttpResponseError as error: process_storage_error(error) @@ -849,6 +862,7 @@ async def set_share_access_policy( timeout=timeout, cls=return_response_headers, lease_id=access_conditions, + file_request_intent=self.file_request_intent, **kwargs ), ) @@ -884,7 +898,9 @@ async def get_share_stats(self, **kwargs: Any) -> int: try: stats = cast( ShareStats, - await self._client.share.get_statistics(timeout=timeout, lease_id=access_conditions, **kwargs), + 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: @@ -973,7 +989,10 @@ async def create_permission_for_share(self, file_permission: str, **kwargs: Any) 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) @@ -1002,7 +1021,11 @@ async def get_permission_for_share(self, permission_key: str, **kwargs: Any) -> return cast( str, await self._client.share.get_permission( - file_permission_key=permission_key, cls=deserialize_permission, timeout=timeout, **kwargs + file_permission_key=permission_key, + cls=deserialize_permission, + timeout=timeout, + file_request_intent=self.file_request_intent, + **kwargs ), ) except HttpResponseError as error: 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 a17a2872381b..a88f17f2fe40 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 @@ -23,7 +23,7 @@ from .._share_service_client_helpers import _parse_url from .._shared.base_client import StorageAccountHostsMixin, parse_query from .._shared.base_client_async import AsyncStorageAccountHostsMixin, AsyncTransportWrapper, parse_connection_str -from .._shared.base_client import _NoOpCredential, _patch_generated_client +from .._client_helpers import _NoOpCredential, _strip_snapshot_from_url from .._shared.parser import _to_utc_datetime from .._shared.policies_async import ExponentialRetry from .._shared.response_handlers import parse_to_internal_user_delegation_key, process_storage_error @@ -133,15 +133,11 @@ def __init__( self.allow_source_trailing_dot = kwargs.pop("allow_source_trailing_dot", None) self.file_request_intent = token_intent self._client = AzureFileStorage( - url=self._base_url, + url=_strip_snapshot_from_url(self.url), credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) - self._client._config.allow_trailing_dot = self.allow_trailing_dot - self._client._config.allow_source_trailing_dot = self.allow_source_trailing_dot - self._client._config.file_request_intent = self.file_request_intent - _patch_generated_client(self._client) async def __aenter__(self) -> Self: await self._client.__aenter__() @@ -281,7 +277,9 @@ async def get_service_properties(self, **kwargs: Any) -> Dict[str, Any]: """ 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) @@ -340,7 +338,9 @@ async def set_service_properties( 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) @@ -396,7 +396,11 @@ def list_shares( results_per_page = kwargs.pop("results_per_page", None) command = functools.partial( - self._client.service.list_shares_segment, include=include, timeout=timeout, **kwargs + self._client.service.list_shares_segment, + include=include, + timeout=timeout, + file_request_intent=self.file_request_intent, + **kwargs, ) return AsyncItemPaged( command, From 15c5f672607f10b04c71073963c01207c2edc335 Mon Sep 17 00:00:00 2001 From: antisch Date: Mon, 23 Mar 2026 19:24:01 +1300 Subject: [PATCH 03/45] Update mock transport --- .../storage/fileshare/_client_helpers.py | 4 + .../tests/test_helpers.py | 121 ++++++++-------- .../tests/test_helpers_async.py | 131 ++++++++---------- 3 files changed, 122 insertions(+), 134 deletions(-) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py index 3172c2d75368..75f8f87f6fc0 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py @@ -19,6 +19,10 @@ def _strip_snapshot_from_url(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 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 532d17c83bbc..8d769ef28c26 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_helpers.py +++ b/sdk/storage/azure-storage-file-share/tests/test_helpers.py @@ -4,13 +4,12 @@ # license information. # -------------------------------------------------------------------------- -from typing import Any, Dict, Optional +from typing import Any, Dict, Iterator, Optional from typing_extensions import Self -from azure.core.pipeline.transport import HttpTransport, RequestsTransportResponse +from azure.core.pipeline.transport import HttpTransport from azure.core.rest import HttpRequest -from requests import Response -from urllib3 import HTTPResponse +from azure.core.rest._http_response_impl import HttpResponseImpl class ProgressTracker: @@ -31,30 +30,48 @@ 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: + def send(self, request: HttpRequest, **kwargs: Any) -> HttpResponseImpl: if request.method == "GET": # download_file headers = { @@ -66,54 +83,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, - ), - ) + 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": # 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": # 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 b5cd7413a1aa..a64d0b75edf6 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,15 +4,11 @@ # license information. # -------------------------------------------------------------------------- -import asyncio -from collections import deque -from typing import Any, Dict, Optional +from typing import Any, AsyncIterator, Dict, Optional -from azure.core.pipeline.transport import AioHttpTransportResponse, AsyncHttpTransport +from azure.core.pipeline.transport import AsyncHttpTransport from azure.core.rest import HttpRequest -from aiohttp import ClientResponse -from aiohttp.streams import StreamReader -from aiohttp.client_proto import ResponseHandler +from azure.core.rest._http_response_impl_async import AsyncHttpResponseImpl class ProgressTracker: @@ -53,31 +49,48 @@ 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: + async def send(self, request: HttpRequest, **kwargs: Any) -> AsyncHttpResponseImpl: if request.method == "GET": # download_file headers = { @@ -89,63 +102,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, - ) + 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": # 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": # 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): From 884eea980fc3a0a2b97f47a7722fd5c0b4ff3c96 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 23 Mar 2026 09:37:00 -0700 Subject: [PATCH 04/45] pylint --- .../azure/storage/fileshare/_deserialize.py | 8 ++-- .../storage/fileshare/_file_client_helpers.py | 2 +- .../azure/storage/fileshare/_models.py | 46 +++++++++++-------- .../azure/storage/fileshare/_parser.py | 3 +- .../azure/storage/fileshare/_serialize.py | 24 ++++++++-- .../fileshare/_share_service_client.py | 4 +- .../azure/storage/fileshare/aio/_models.py | 17 +++---- .../aio/_share_service_client_async.py | 4 +- 8 files changed, 68 insertions(+), 40 deletions(-) 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 4676c4da96d3..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 @@ -79,16 +79,16 @@ def deserialize_file_stream( # Extracts out file permission -def deserialize_permission( +def deserialize_permission( # pylint: disable=unused-argument response: "PipelineResponse", obj: Any, headers: Dict[str, Any] -) -> Optional[str]: # pylint: disable=unused-argument +) -> Optional[str]: return cast(Optional[str], obj.permission) # Extracts out file permission key -def deserialize_permission_key( +def deserialize_permission_key( # pylint: disable=unused-argument response: "PipelineResponse", obj: Any, headers: Dict[str, Any] -) -> Optional[str]: # pylint: disable=unused-argument +) -> Optional[str]: if response is None or headers is None: return None return cast(Optional[str], headers.get("x-ms-file-permission-key", None)) 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 2278527e9c1f..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 @@ -75,7 +75,7 @@ def _upload_range_from_url_options( 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) + _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) 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 cc81807580f2..f0b1fe411114 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 @@ -9,6 +9,9 @@ from enum import Enum from typing import Any, Callable, Dict, List, Literal, Optional, Union, TYPE_CHECKING from urllib.parse import unquote + +import datetime as _datetime_module + from typing_extensions import Self from azure.core import CaseInsensitiveEnumMeta @@ -31,15 +34,19 @@ from ._shared.models import DictMixin, get_enum_value from ._shared.response_handlers import process_storage_error, return_context_and_deserialized -import datetime as _datetime_module - if TYPE_CHECKING: from datetime import datetime from ._generated.models import ShareRootSquash def _parse_datetime(value): - """Parse a datetime value that may already be a datetime object (new generated code) or a string (old).""" + """Parse a datetime value that may already be a datetime object (new generated code) or a string (old). + + :param value: The value to parse. + :type value: str or ~datetime.datetime or None + :returns: A datetime object or None. + :rtype: ~datetime.datetime or None + """ if value is None: return None if isinstance(value, _datetime_module.datetime): @@ -135,9 +142,9 @@ def _from_generated(cls, generated): version=generated.version, enabled=generated.enabled, include_apis=generated.include_apis, - retention_policy=RetentionPolicy._from_generated( + retention_policy=RetentionPolicy._from_generated( # pylint: disable=protected-access generated.retention_policy - ), # pylint: disable=protected-access + ), ) @@ -232,7 +239,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._data = {} self.enabled = enabled @@ -246,7 +253,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._data = {} self.required = required @@ -263,7 +270,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, @@ -286,7 +293,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._data = {} self.required = required @@ -300,7 +307,7 @@ 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__(self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any) -> None: # pylint: disable=unused-argument self._data = {} self.encryption_in_transit = encryption_in_transit @@ -319,7 +326,7 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): nfs: Optional[ShareNfsSettings] """Sets the NFS settings.""" - def __init__( + def __init__( # pylint: disable=unused-argument self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any ) -> None: self._data = {} @@ -764,8 +771,8 @@ def _extract_data_cb(self, get_next_return): 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 + 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 @@ -881,8 +888,8 @@ def _get_next_cb(self, continuation_token): 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 + 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 @@ -1135,11 +1142,12 @@ def _extract_data_cb(self, get_next_return): 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 + DirectoryProperties._from_generated(i) # pylint: disable=protected-access + 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: disable = protected-access + [FileProperties._from_generated(i) for i in self._response.segment.file_items] # pylint: disable=protected-access + ) return self._response.next_marker or None, self.current_page 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 463dff13deac..7323a1f35fa5 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 @@ -11,7 +11,8 @@ _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" + "Size of file_permission is too large. file_permission should be <=8KB, else " + "please use file_permission_key" ) 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 862d8f83057d..cf684a51331c 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 @@ -85,7 +85,13 @@ def get_source_conditions(kwargs: Dict[str, Any]) -> Dict[str, Any]: 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.""" + """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"): @@ -96,7 +102,13 @@ def get_access_conditions(lease: Optional[Union["ShareLeaseClient", "ShareLeaseC def get_source_access_conditions( lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]] ) -> Optional[str]: - """Extract source_lease_id from a lease client or string. Returns the lease_id string or None.""" + """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"): @@ -107,7 +119,13 @@ def get_source_access_conditions( def get_dest_access_conditions( lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]] ) -> Optional[str]: - """Extract destination_lease_id from a lease client or string. Returns the lease_id string or None.""" + """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"): 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 e802345fd0a0..f0914d2a585a 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 @@ -517,8 +517,8 @@ 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 + 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, 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 0aa13391ef2d..e8668a6c88b8 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 @@ -83,8 +83,8 @@ async def _extract_data_cb(self, get_next_return): 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 + 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 @@ -132,8 +132,8 @@ async def _get_next_cb(self, continuation_token): 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 + 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 @@ -202,9 +202,10 @@ async def _extract_data_cb(self, get_next_return): 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 + DirectoryProperties._from_generated(i) # pylint: disable=protected-access + 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: disable = protected-access + [FileProperties._from_generated(i) for i in self._response.segment.file_items] # pylint: disable=protected-access + ) return self._response.next_marker or None, self.current_page 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 a88f17f2fe40..24a3b2daf8a5 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 @@ -519,8 +519,8 @@ 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 + 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, From 98e094a19afa4a37c83fe52cee47f826f4588fee Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 23 Mar 2026 10:14:21 -0700 Subject: [PATCH 05/45] adding accept sanitization to conftest --- .../fileshare/_generated/operations/_patch.py | 64 +------------------ .../tests/conftest.py | 3 + 2 files changed, 4 insertions(+), 63 deletions(-) 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 8029044b14be..0deed5571313 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 @@ -36,51 +36,6 @@ "build_file_start_copy_request", ] -# Build functions missing Accept header -_MISSING_ACCEPT_FUNCTIONS = [ - "build_service_set_properties_request", - "build_share_create_request", - "build_share_get_properties_request", - "build_share_delete_request", - "build_share_acquire_lease_request", - "build_share_release_lease_request", - "build_share_change_lease_request", - "build_share_renew_lease_request", - "build_share_break_lease_request", - "build_share_create_snapshot_request", - "build_share_create_permission_request", - "build_share_set_properties_request", - "build_share_set_metadata_request", - "build_share_set_access_policy_request", - "build_share_restore_request", - "build_directory_create_request", - "build_directory_get_properties_request", - "build_directory_delete_request", - "build_directory_set_properties_request", - "build_directory_set_metadata_request", - "build_directory_force_close_handles_request", - "build_directory_rename_request", - "build_file_create_request", - "build_file_get_properties_request", - "build_file_delete_request", - "build_file_set_http_headers_request", - "build_file_set_metadata_request", - "build_file_acquire_lease_request", - "build_file_release_lease_request", - "build_file_change_lease_request", - "build_file_break_lease_request", - "build_file_upload_range_request", - "build_file_upload_range_from_url_request", - "build_file_start_copy_request", - "build_file_abort_copy_request", - "build_file_force_close_handles_request", - "build_file_rename_request", - "build_file_create_symbolic_link_request", - "build_file_get_symbolic_link_request", - "build_file_create_hard_link_request", -] - - def _fix_trailing_slash(build_fn): """Wrap a build_*_request function to strip the trailing slash from _url = "/".""" @@ -95,19 +50,6 @@ def wrapper(*args, **kwargs): return wrapper -def _fix_accept_header(build_fn): - """Wrap a build_*_request function to add Accept: application/xml if missing.""" - - @functools.wraps(build_fn) - def wrapper(*args, **kwargs): - request = build_fn(*args, **kwargs) - if "Accept" not in request.headers: - request.headers["Accept"] = "application/xml" - return request - - return wrapper - - def patch_sdk(): """Do not remove from this file. @@ -117,8 +59,4 @@ def patch_sdk(): """ for fn_name in _TRAILING_SLASH_FUNCTIONS: original = getattr(_operations, fn_name) - setattr(_operations, fn_name, _fix_trailing_slash(original)) - - for fn_name in _MISSING_ACCEPT_FUNCTIONS: - original = getattr(_operations, fn_name) - setattr(_operations, fn_name, _fix_accept_header(original)) + setattr(_operations, fn_name, _fix_trailing_slash(original)) \ No newline at end of file diff --git a/sdk/storage/azure-storage-file-share/tests/conftest.py b/sdk/storage/azure-storage-file-share/tests/conftest.py index d29d472cef15..c711ae3a33ec 100644 --- a/sdk/storage/azure-storage-file-share/tests/conftest.py +++ b/sdk/storage/azure-storage-file-share/tests/conftest.py @@ -16,6 +16,7 @@ add_oauth_response_sanitizer, add_uri_string_sanitizer, set_custom_default_matcher, + add_remove_header_sanitizer, test_proxy, ) @@ -38,3 +39,5 @@ def add_sanitizers(test_proxy): # TypeSpec-generated code may order query parameters differently than AutoRest set_custom_default_matcher(ignore_query_ordering=True) + + add_remove_header_sanitizer(headers="Accept") From 72fe218d24629a387004cd984220119f0e84b2b4 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 24 Mar 2026 12:09:14 -0700 Subject: [PATCH 06/45] pin new version of azure-core --- sdk/storage/azure-storage-file-share/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index 2f1582cfc5b8..a9a3c3d0ce7f 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -32,7 +32,7 @@ keywords = ["azure", "azure sdk"] dependencies = [ "isodate>=0.6.1", - "azure-core>=1.37.0", + "azure-core>=1.38.3", "typing-extensions>=4.6.0", ] dynamic = [ From cee5a02089e1bb83041e95945f66fabc21856293 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 26 Mar 2026 10:16:24 -0700 Subject: [PATCH 07/45] regen --- .../azure-storage-file-share/MANIFEST.in | 3 +- .../apiview-properties.json | 310 +++++++------- .../storage/fileshare/_directory_client.py | 2 +- .../azure/storage/fileshare/_file_client.py | 2 +- .../storage/fileshare/_generated/__init__.py | 4 +- .../storage/fileshare/_generated/_client.py | 18 +- .../fileshare/_generated/_configuration.py | 8 +- .../storage/fileshare/_generated/_patch.py | 121 +++++- .../fileshare/_generated/aio/__init__.py | 4 +- .../fileshare/_generated/aio/_client.py | 18 +- .../_generated/aio/_configuration.py | 8 +- .../fileshare/_generated/aio/_patch.py | 120 +++++- .../_generated/aio/operations/_operations.py | 346 +++++++++------- .../fileshare/_generated/models/__init__.py | 8 +- .../fileshare/_generated/models/_enums.py | 2 +- .../fileshare/_generated/models/_models.py | 320 +++++++-------- .../_generated/operations/_operations.py | 378 ++++++++++-------- .../fileshare/_generated/operations/_patch.py | 3 +- .../storage/fileshare/_generated/py.typed | 1 + .../azure/storage/fileshare/_models.py | 14 +- .../azure/storage/fileshare/_parser.py | 3 +- .../azure/storage/fileshare/_share_client.py | 2 +- .../fileshare/_share_service_client.py | 2 +- .../fileshare/_shared/response_handlers.py | 31 +- .../fileshare/aio/_directory_client_async.py | 2 +- .../fileshare/aio/_file_client_async.py | 2 +- .../azure/storage/fileshare/aio/_models.py | 4 +- .../fileshare/aio/_share_client_async.py | 2 +- .../aio/_share_service_client_async.py | 2 +- .../azure-storage-file-share/pyproject.toml | 3 +- sdk/storage/azure-storage-file-share/setup.py | 75 ---- .../tests/test_helpers.py | 3 + .../tests/test_helpers_async.py | 3 + .../tsp-location.yaml | 6 +- 34 files changed, 1078 insertions(+), 752 deletions(-) create mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/py.typed delete mode 100644 sdk/storage/azure-storage-file-share/setup.py diff --git a/sdk/storage/azure-storage-file-share/MANIFEST.in b/sdk/storage/azure-storage-file-share/MANIFEST.in index 1da294d9d659..6267830e6cc6 100644 --- a/sdk/storage/azure-storage-file-share/MANIFEST.in +++ b/sdk/storage/azure-storage-file-share/MANIFEST.in @@ -1,7 +1,8 @@ include *.md include LICENSE -include azure/storage/fileshare/py.typed +include azure/storage/fileshare/_generated/py.typed recursive-include tests *.py recursive-include samples *.py *.md include azure/__init__.py include azure/storage/__init__.py +include azure/storage/fileshare/__init__.py diff --git a/sdk/storage/azure-storage-file-share/apiview-properties.json b/sdk/storage/azure-storage-file-share/apiview-properties.json index 7e0487b5c18f..629919ac0239 100644 --- a/sdk/storage/azure-storage-file-share/apiview-properties.json +++ b/sdk/storage/azure-storage-file-share/apiview-properties.json @@ -1,160 +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.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.StorageError": "Storage.File.Error", - "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.StorageErrorCode": "Storage.File.StorageErrorCode", - "azure.storage.fileshare.models.ShareTokenIntent": "Storage.File.ShareTokenIntent", - "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.models.FilePermissionFormat": "Storage.File.FilePermissionFormat", - "azure.storage.fileshare.models.NfsFileType": "Storage.File.NfsFileType", - "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.CopyStatusType": "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.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", - "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._generated.models.AccessPolicy": "Storage.File.AccessPolicy", + "azure.storage.fileshare._generated.models.ClearRange": "Storage.File.ClearRange", + "azure.storage.fileshare._generated.models.CorsRule": "Storage.File.CorsRule", + "azure.storage.fileshare._generated.models.DirectoryItem": "Storage.File.DirectoryItem", + "azure.storage.fileshare._generated.models.Error": "Storage.File.Error", + "azure.storage.fileshare._generated.models.FileItem": "Storage.File.FileItem", + "azure.storage.fileshare._generated.models.FileProperty": "Storage.File.FileProperty", + "azure.storage.fileshare._generated.models.FileRange": "Storage.File.FileRange", + "azure.storage.fileshare._generated.models.FilesAndDirectoriesListSegment": "Storage.File.FilesAndDirectoriesListSegment", + "azure.storage.fileshare._generated.models.HandleItem": "Storage.File.HandleItem", + "azure.storage.fileshare._generated.models.KeyInfo": "Storage.File.KeyInfo", + "azure.storage.fileshare._generated.models.ListFilesAndDirectoriesSegmentResponse": "Storage.File.ListFilesAndDirectoriesSegmentResponse", + "azure.storage.fileshare._generated.models.ListHandlesResponse": "Storage.File.ListHandlesResponse", + "azure.storage.fileshare._generated.models.ListSharesResponse": "Storage.File.ListSharesResponse", + "azure.storage.fileshare._generated.models.Metrics": "Storage.File.Metrics", + "azure.storage.fileshare._generated.models.RetentionPolicy": "Storage.File.RetentionPolicy", + "azure.storage.fileshare._generated.models.ShareFileRangeList": "Storage.File.ShareFileRangeList", + "azure.storage.fileshare._generated.models.ShareItemInternal": "Storage.File.ShareItemInternal", + "azure.storage.fileshare._generated.models.ShareNfsSettings": "Storage.File.ShareNfsSettings", + "azure.storage.fileshare._generated.models.ShareNfsSettingsEncryptionInTransit": "Storage.File.ShareNfsSettingsEncryptionInTransit", + "azure.storage.fileshare._generated.models.SharePermission": "Storage.File.SharePermission", + "azure.storage.fileshare._generated.models.SharePropertiesInternal": "Storage.File.SharePropertiesInternal", + "azure.storage.fileshare._generated.models.ShareProtocolSettings": "Storage.File.ShareProtocolSettings", + "azure.storage.fileshare._generated.models.ShareSmbSettings": "Storage.File.ShareSmbSettings", + "azure.storage.fileshare._generated.models.ShareSmbSettingsEncryptionInTransit": "Storage.File.ShareSmbSettingsEncryptionInTransit", + "azure.storage.fileshare._generated.models.ShareStats": "Storage.File.ShareStats", + "azure.storage.fileshare._generated.models.SignedIdentifier": "Storage.File.SignedIdentifier", + "azure.storage.fileshare._generated.models.SignedIdentifiers": "Storage.File.SignedIdentifiers", + "azure.storage.fileshare._generated.models.SmbMultichannel": "Storage.File.SmbMultichannel", + "azure.storage.fileshare._generated.models.StorageServiceProperties": "Storage.File.StorageServiceProperties", + "azure.storage.fileshare._generated.models.StringEncoded": "Storage.File.StringEncoded", + "azure.storage.fileshare._generated.models.UserDelegationKey": "Storage.File.UserDelegationKey", + "azure.storage.fileshare._generated.models.StorageErrorCode": "Storage.File.StorageErrorCode", + "azure.storage.fileshare._generated.models.ShareTokenIntent": "Storage.File.ShareTokenIntent", + "azure.storage.fileshare._generated.models.LeaseStatusType": "Storage.File.LeaseStatusType", + "azure.storage.fileshare._generated.models.LeaseStateType": "Storage.File.LeaseStateType", + "azure.storage.fileshare._generated.models.LeaseDurationType": "Storage.File.LeaseDurationType", + "azure.storage.fileshare._generated.models.ShareRootSquash": "Storage.File.ShareRootSquash", + "azure.storage.fileshare._generated.models.ListSharesIncludeType": "Storage.File.ListSharesIncludeType", + "azure.storage.fileshare._generated.models.ShareAccessTier": "Storage.File.ShareAccessTier", + "azure.storage.fileshare._generated.models.DeleteSnapshotsOptionType": "Storage.File.DeleteSnapshotsOptionType", + "azure.storage.fileshare._generated.models.FilePermissionFormat": "Storage.File.FilePermissionFormat", + "azure.storage.fileshare._generated.models.NfsFileType": "Storage.File.NfsFileType", + "azure.storage.fileshare._generated.models.FilePropertySemantics": "Storage.File.FilePropertySemantics", + "azure.storage.fileshare._generated.models.ListFilesIncludeType": "Storage.File.ListFilesIncludeType", + "azure.storage.fileshare._generated.models.AccessRight": "Storage.File.AccessRight", + "azure.storage.fileshare._generated.models.CopyStatus": "Storage.File.CopyStatus", + "azure.storage.fileshare._generated.models.FileRangeWriteType": "Storage.File.FileRangeWriteType", + "azure.storage.fileshare._generated.models.FileLastWrittenMode": "Storage.File.FileLastWrittenMode", + "azure.storage.fileshare._generated.models.FileRangeWriteFromUrlType": "Storage.File.FileRangeWriteFromUrlType", + "azure.storage.fileshare._generated.models.PermissionCopyModeType": "Storage.File.PermissionCopyModeType", + "azure.storage.fileshare._generated.models.ModeCopyMode": "Storage.File.ModeCopyMode", + "azure.storage.fileshare._generated.models.OwnerCopyMode": "Storage.File.OwnerCopyMode", + "azure.storage.fileshare._generated.operations.ServiceOperations.set_properties": "Storage.File.Service.setProperties", + "azure.storage.fileshare._generated.aio.operations.ServiceOperations.set_properties": "Storage.File.Service.setProperties", + "azure.storage.fileshare._generated.operations.ServiceOperations.get_properties": "Storage.File.Service.getProperties", + "azure.storage.fileshare._generated.aio.operations.ServiceOperations.get_properties": "Storage.File.Service.getProperties", + "azure.storage.fileshare._generated.operations.ServiceOperations.list_shares_segment": "Storage.File.Service.listSharesSegment", + "azure.storage.fileshare._generated.aio.operations.ServiceOperations.list_shares_segment": "Storage.File.Service.listSharesSegment", + "azure.storage.fileshare._generated.operations.ServiceOperations.get_user_delegation_key": "Storage.File.Service.getUserDelegationKey", + "azure.storage.fileshare._generated.aio.operations.ServiceOperations.get_user_delegation_key": "Storage.File.Service.getUserDelegationKey", + "azure.storage.fileshare._generated.operations.ShareOperations.create": "Storage.File.Share.create", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.create": "Storage.File.Share.create", + "azure.storage.fileshare._generated.operations.ShareOperations.get_properties": "Storage.File.Share.getProperties", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.get_properties": "Storage.File.Share.getProperties", + "azure.storage.fileshare._generated.operations.ShareOperations.delete": "Storage.File.Share.delete", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.delete": "Storage.File.Share.delete", + "azure.storage.fileshare._generated.operations.ShareOperations.acquire_lease": "Storage.File.Share.acquireLease", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.acquire_lease": "Storage.File.Share.acquireLease", + "azure.storage.fileshare._generated.operations.ShareOperations.release_lease": "Storage.File.Share.releaseLease", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.release_lease": "Storage.File.Share.releaseLease", + "azure.storage.fileshare._generated.operations.ShareOperations.change_lease": "Storage.File.Share.changeLease", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.change_lease": "Storage.File.Share.changeLease", + "azure.storage.fileshare._generated.operations.ShareOperations.renew_lease": "Storage.File.Share.renewLease", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.renew_lease": "Storage.File.Share.renewLease", + "azure.storage.fileshare._generated.operations.ShareOperations.break_lease": "Storage.File.Share.breakLease", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.break_lease": "Storage.File.Share.breakLease", + "azure.storage.fileshare._generated.operations.ShareOperations.create_snapshot": "Storage.File.Share.createSnapshot", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.create_snapshot": "Storage.File.Share.createSnapshot", + "azure.storage.fileshare._generated.operations.ShareOperations.create_permission": "Storage.File.Share.createPermission", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.create_permission": "Storage.File.Share.createPermission", + "azure.storage.fileshare._generated.operations.ShareOperations.get_permission": "Storage.File.Share.getPermission", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.get_permission": "Storage.File.Share.getPermission", + "azure.storage.fileshare._generated.operations.ShareOperations.set_properties": "Storage.File.Share.setProperties", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.set_properties": "Storage.File.Share.setProperties", + "azure.storage.fileshare._generated.operations.ShareOperations.set_metadata": "Storage.File.Share.setMetadata", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.set_metadata": "Storage.File.Share.setMetadata", + "azure.storage.fileshare._generated.operations.ShareOperations.get_access_policy": "Storage.File.Share.getAccessPolicy", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.get_access_policy": "Storage.File.Share.getAccessPolicy", + "azure.storage.fileshare._generated.operations.ShareOperations.set_access_policy": "Storage.File.Share.setAccessPolicy", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.set_access_policy": "Storage.File.Share.setAccessPolicy", + "azure.storage.fileshare._generated.operations.ShareOperations.get_statistics": "Storage.File.Share.getStatistics", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.get_statistics": "Storage.File.Share.getStatistics", + "azure.storage.fileshare._generated.operations.ShareOperations.restore": "Storage.File.Share.restore", + "azure.storage.fileshare._generated.aio.operations.ShareOperations.restore": "Storage.File.Share.restore", + "azure.storage.fileshare._generated.operations.DirectoryOperations.create": "Storage.File.Directory.create", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.create": "Storage.File.Directory.create", + "azure.storage.fileshare._generated.operations.DirectoryOperations.get_properties": "Storage.File.Directory.getProperties", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.get_properties": "Storage.File.Directory.getProperties", + "azure.storage.fileshare._generated.operations.DirectoryOperations.delete": "Storage.File.Directory.delete", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.delete": "Storage.File.Directory.delete", + "azure.storage.fileshare._generated.operations.DirectoryOperations.set_properties": "Storage.File.Directory.setProperties", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.set_properties": "Storage.File.Directory.setProperties", + "azure.storage.fileshare._generated.operations.DirectoryOperations.set_metadata": "Storage.File.Directory.setMetadata", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.set_metadata": "Storage.File.Directory.setMetadata", + "azure.storage.fileshare._generated.operations.DirectoryOperations.list_files_and_directories_segment": "Storage.File.Directory.listFilesAndDirectoriesSegment", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.list_files_and_directories_segment": "Storage.File.Directory.listFilesAndDirectoriesSegment", + "azure.storage.fileshare._generated.operations.DirectoryOperations.list_handles": "Storage.File.Directory.listHandles", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.list_handles": "Storage.File.Directory.listHandles", + "azure.storage.fileshare._generated.operations.DirectoryOperations.force_close_handles": "Storage.File.Directory.forceCloseHandles", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.force_close_handles": "Storage.File.Directory.forceCloseHandles", + "azure.storage.fileshare._generated.operations.DirectoryOperations.rename": "Storage.File.Directory.rename", + "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.rename": "Storage.File.Directory.rename", + "azure.storage.fileshare._generated.operations.FileOperations.create": "Storage.File.File.create", + "azure.storage.fileshare._generated.aio.operations.FileOperations.create": "Storage.File.File.create", + "azure.storage.fileshare._generated.operations.FileOperations.download": "Storage.File.File.download", + "azure.storage.fileshare._generated.aio.operations.FileOperations.download": "Storage.File.File.download", + "azure.storage.fileshare._generated.operations.FileOperations.get_properties": "Storage.File.File.getProperties", + "azure.storage.fileshare._generated.aio.operations.FileOperations.get_properties": "Storage.File.File.getProperties", + "azure.storage.fileshare._generated.operations.FileOperations.delete": "Storage.File.File.delete", + "azure.storage.fileshare._generated.aio.operations.FileOperations.delete": "Storage.File.File.delete", + "azure.storage.fileshare._generated.operations.FileOperations.set_http_headers": "Storage.File.File.setHttpHeaders", + "azure.storage.fileshare._generated.aio.operations.FileOperations.set_http_headers": "Storage.File.File.setHttpHeaders", + "azure.storage.fileshare._generated.operations.FileOperations.set_metadata": "Storage.File.File.setMetadata", + "azure.storage.fileshare._generated.aio.operations.FileOperations.set_metadata": "Storage.File.File.setMetadata", + "azure.storage.fileshare._generated.operations.FileOperations.acquire_lease": "Storage.File.File.acquireLease", + "azure.storage.fileshare._generated.aio.operations.FileOperations.acquire_lease": "Storage.File.File.acquireLease", + "azure.storage.fileshare._generated.operations.FileOperations.release_lease": "Storage.File.File.releaseLease", + "azure.storage.fileshare._generated.aio.operations.FileOperations.release_lease": "Storage.File.File.releaseLease", + "azure.storage.fileshare._generated.operations.FileOperations.change_lease": "Storage.File.File.changeLease", + "azure.storage.fileshare._generated.aio.operations.FileOperations.change_lease": "Storage.File.File.changeLease", + "azure.storage.fileshare._generated.operations.FileOperations.break_lease": "Storage.File.File.breakLease", + "azure.storage.fileshare._generated.aio.operations.FileOperations.break_lease": "Storage.File.File.breakLease", + "azure.storage.fileshare._generated.operations.FileOperations.upload_range": "Storage.File.File.uploadRange", + "azure.storage.fileshare._generated.aio.operations.FileOperations.upload_range": "Storage.File.File.uploadRange", + "azure.storage.fileshare._generated.operations.FileOperations.upload_range_from_url": "Storage.File.File.uploadRangeFromUrl", + "azure.storage.fileshare._generated.aio.operations.FileOperations.upload_range_from_url": "Storage.File.File.uploadRangeFromUrl", + "azure.storage.fileshare._generated.operations.FileOperations.get_range_list": "Storage.File.File.getRangeList", + "azure.storage.fileshare._generated.aio.operations.FileOperations.get_range_list": "Storage.File.File.getRangeList", + "azure.storage.fileshare._generated.operations.FileOperations.start_copy": "Storage.File.File.startCopy", + "azure.storage.fileshare._generated.aio.operations.FileOperations.start_copy": "Storage.File.File.startCopy", + "azure.storage.fileshare._generated.operations.FileOperations.abort_copy": "Storage.File.File.abortCopy", + "azure.storage.fileshare._generated.aio.operations.FileOperations.abort_copy": "Storage.File.File.abortCopy", + "azure.storage.fileshare._generated.operations.FileOperations.list_handles": "Storage.File.File.listHandles", + "azure.storage.fileshare._generated.aio.operations.FileOperations.list_handles": "Storage.File.File.listHandles", + "azure.storage.fileshare._generated.operations.FileOperations.force_close_handles": "Storage.File.File.forceCloseHandles", + "azure.storage.fileshare._generated.aio.operations.FileOperations.force_close_handles": "Storage.File.File.forceCloseHandles", + "azure.storage.fileshare._generated.operations.FileOperations.rename": "Storage.File.File.rename", + "azure.storage.fileshare._generated.aio.operations.FileOperations.rename": "Storage.File.File.rename", + "azure.storage.fileshare._generated.operations.FileOperations.create_symbolic_link": "Storage.File.File.createSymbolicLink", + "azure.storage.fileshare._generated.aio.operations.FileOperations.create_symbolic_link": "Storage.File.File.createSymbolicLink", + "azure.storage.fileshare._generated.operations.FileOperations.get_symbolic_link": "Storage.File.File.getSymbolicLink", + "azure.storage.fileshare._generated.aio.operations.FileOperations.get_symbolic_link": "Storage.File.File.getSymbolicLink", + "azure.storage.fileshare._generated.operations.FileOperations.create_hard_link": "Storage.File.File.createHardLink", + "azure.storage.fileshare._generated.aio.operations.FileOperations.create_hard_link": "Storage.File.File.createHardLink" } } \ No newline at end of file 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 b6ad8f4c15d4..8fb87b57ad96 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 @@ -20,7 +20,7 @@ from ._deserialize import deserialize_directory_properties from ._directory_client_helpers import _format_url, _from_directory_url, _parse_url from ._file_client import ShareFileClient -from ._generated import AzureFileStorageClient as 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 ._serialize import get_api_version, get_dest_access_conditions, get_rename_smb_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 7fea6b4e6e8c..fcf20f28cdbb 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 @@ -25,7 +25,7 @@ _parse_url, _upload_range_from_url_options, ) -from ._generated import AzureFileStorageClient as AzureFileStorage +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 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 09977481fd57..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 @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._client import AzureFileStorageClient # type: ignore +from ._client import FileClient # type: ignore from ._version import VERSION __version__ = VERSION @@ -25,7 +25,7 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AzureFileStorageClient", + "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/_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py index 0976b08a001c..1d46a86c7891 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py @@ -14,7 +14,7 @@ from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from ._configuration import AzureFileStorageClientConfiguration +from ._configuration import FileClientConfiguration from ._utils.serialization import Deserializer, Serializer from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations @@ -22,31 +22,31 @@ from azure.core.credentials import TokenCredential -class AzureFileStorageClient: # pylint: disable=client-accepts-api-version-keyword +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 service: ServiceOperations operations - :vartype service: azure.storage.fileshare.operations.ServiceOperations + :vartype service: azure.storage.fileshare._generated.operations.ServiceOperations :ivar share: ShareOperations operations - :vartype share: azure.storage.fileshare.operations.ShareOperations + :vartype share: azure.storage.fileshare._generated.operations.ShareOperations :ivar directory: DirectoryOperations operations - :vartype directory: azure.storage.fileshare.operations.DirectoryOperations + :vartype directory: azure.storage.fileshare._generated.operations.DirectoryOperations :ivar file: FileOperations operations - :vartype file: azure.storage.fileshare.operations.FileOperations + :vartype file: azure.storage.fileshare._generated.operations.FileOperations :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. Required. :type credential: ~azure.core.credentials.TokenCredential :keyword version: Specifies the version of the operation to use for this request. Known values - are "2026-04-06" and None. Default value is "2026-04-06". Note that overriding this default - value may result in unsupported behavior. + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. :paramtype version: str """ def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> None: _endpoint = "{url}" - self._config = AzureFileStorageClientConfiguration(url=url, credential=credential, **kwargs) + self._config = FileClientConfiguration(url=url, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is 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 e5c597611dcd..5fbde0018e32 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 @@ -16,8 +16,8 @@ from azure.core.credentials import TokenCredential -class AzureFileStorageClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for AzureFileStorageClient. +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. @@ -28,8 +28,8 @@ class AzureFileStorageClientConfiguration: # pylint: disable=too-many-instance- :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-04-06" and None. Default value is "2026-04-06". Note that overriding this default - value may result in unsupported behavior. + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. :paramtype version: str """ 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 87676c65a8f0..97c2db61e797 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 @@ -7,9 +7,128 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Optional, TYPE_CHECKING +from azure.core import PipelineClient +from azure.core.pipeline import Pipeline, PipelineRequest +from azure.core.pipeline.policies import SansIOHTTPPolicy -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +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-04-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/aio/__init__.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/__init__.py index 632a0dd26299..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 @@ -12,7 +12,7 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._client import AzureFileStorageClient # 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__ = [ - "AzureFileStorageClient", + "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/_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py index 9ad33aa04f97..52e67efdb6ca 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py @@ -15,38 +15,38 @@ from azure.core.rest import AsyncHttpResponse, HttpRequest from .._utils.serialization import Deserializer, Serializer -from ._configuration import AzureFileStorageClientConfiguration +from ._configuration import FileClientConfiguration from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential -class AzureFileStorageClient: # pylint: disable=client-accepts-api-version-keyword +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 service: ServiceOperations operations - :vartype service: azure.storage.fileshare.aio.operations.ServiceOperations + :vartype service: azure.storage.fileshare._generated.aio.operations.ServiceOperations :ivar share: ShareOperations operations - :vartype share: azure.storage.fileshare.aio.operations.ShareOperations + :vartype share: azure.storage.fileshare._generated.aio.operations.ShareOperations :ivar directory: DirectoryOperations operations - :vartype directory: azure.storage.fileshare.aio.operations.DirectoryOperations + :vartype directory: azure.storage.fileshare._generated.aio.operations.DirectoryOperations :ivar file: FileOperations operations - :vartype file: azure.storage.fileshare.aio.operations.FileOperations + :vartype file: azure.storage.fileshare._generated.aio.operations.FileOperations :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. 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-04-06" and None. Default value is "2026-04-06". Note that overriding this default - value may result in unsupported behavior. + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. :paramtype version: str """ def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: _endpoint = "{url}" - self._config = AzureFileStorageClientConfiguration(url=url, credential=credential, **kwargs) + self._config = FileClientConfiguration(url=url, credential=credential, **kwargs) _policies = kwargs.pop("policies", None) if _policies is 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 efb1b5dbdf99..3dfaf3a4772d 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 @@ -16,8 +16,8 @@ from azure.core.credentials_async import AsyncTokenCredential -class AzureFileStorageClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for AzureFileStorageClient. +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. @@ -28,8 +28,8 @@ class AzureFileStorageClientConfiguration: # pylint: disable=too-many-instance- :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-04-06" and None. Default value is "2026-04-06". Note that overriding this default - value may result in unsupported behavior. + are "2026-04-06". Default value is "2026-04-06". Note that overriding this default value may + result in unsupported behavior. :paramtype version: str """ 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 87676c65a8f0..3cdf362eaca3 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 @@ -7,9 +7,127 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import Any, Optional, TYPE_CHECKING +from azure.core import AsyncPipelineClient +from azure.core.pipeline import AsyncPipeline, PipelineRequest +from azure.core.pipeline.policies import SansIOHTTPPolicy -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level +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-04-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/_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_operations.py index f3d29a1de455..3ed33ee58d63 100644 --- 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 @@ -83,7 +83,7 @@ build_share_set_metadata_request, build_share_set_properties_request, ) -from .._configuration import AzureFileStorageClientConfiguration +from .._configuration import FileClientConfiguration T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] @@ -96,14 +96,14 @@ class ServiceOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare.aio.AzureFileStorageClient`'s + :class:`~azure.storage.fileshare._generated.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: AzureFileStorageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + 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") @@ -125,7 +125,8 @@ async def set_properties( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -170,7 +171,7 @@ async def set_properties( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -200,7 +201,8 @@ async def get_properties( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: StorageServiceProperties. The StorageServiceProperties is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.StorageServiceProperties @@ -247,7 +249,7 @@ async def get_properties( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -297,10 +299,12 @@ async def list_shares_segment( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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] + :paramtype include: list[str or + ~azure.storage.fileshare._generated.models.ListSharesIncludeType] :return: ListSharesResponse. The ListSharesResponse is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ListSharesResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -350,7 +354,7 @@ async def list_shares_segment( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -434,7 +438,7 @@ async def get_user_delegation_key( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -465,14 +469,14 @@ class ShareOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare.aio.AzureFileStorageClient`'s + :class:`~azure.storage.fileshare._generated.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: AzureFileStorageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + 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") @@ -507,12 +511,12 @@ async def create( # pylint: disable=too-many-locals :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 + :paramtype access_tier: str or ~azure.storage.fileshare._generated.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 + :paramtype root_squash: str or ~azure.storage.fileshare._generated.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 @@ -528,7 +532,8 @@ async def create( # pylint: disable=too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :keyword share_provisioned_iops: Optional. Specifies the provisioned IOPS of the share. Default value is None. :paramtype share_provisioned_iops: int @@ -589,7 +594,7 @@ async def create( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -639,7 +644,8 @@ async def get_properties( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -684,7 +690,7 @@ async def get_properties( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -781,9 +787,11 @@ async def delete( :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 + :paramtype delete_snapshots: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -829,7 +837,7 @@ async def delete( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -879,7 +887,8 @@ async def acquire_lease( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -924,7 +933,7 @@ async def acquire_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -964,7 +973,8 @@ async def release_lease( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1008,7 +1018,7 @@ async def release_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1052,7 +1062,8 @@ async def change_lease( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1097,7 +1108,7 @@ async def change_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1137,7 +1148,8 @@ async def renew_lease( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1181,7 +1193,7 @@ async def renew_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1231,7 +1243,8 @@ async def break_lease( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1276,7 +1289,7 @@ async def break_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1312,7 +1325,8 @@ async def create_snapshot( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1353,7 +1367,7 @@ async def create_snapshot( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1393,7 +1407,8 @@ async def create_permission( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1420,7 +1435,8 @@ async def create_permission( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1447,7 +1463,8 @@ async def create_permission( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1472,7 +1489,8 @@ async def create_permission( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1522,7 +1540,7 @@ async def create_permission( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1562,9 +1580,11 @@ async def get_permission( :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: SharePermission. The SharePermission is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.SharePermission :raises ~azure.core.exceptions.HttpResponseError: @@ -1612,7 +1632,7 @@ async def get_permission( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1663,13 +1683,13 @@ async def set_properties( # pylint: disable=too-many-locals :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 + :paramtype access_tier: str or ~azure.storage.fileshare._generated.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 + :paramtype root_squash: str or ~azure.storage.fileshare._generated.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 @@ -1685,7 +1705,8 @@ async def set_properties( # pylint: disable=too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :keyword share_provisioned_iops: Optional. Specifies the provisioned number of input/output operations per second (IOPS) of the share. Default value is None. :paramtype share_provisioned_iops: int @@ -1745,7 +1766,7 @@ async def set_properties( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1805,7 +1826,8 @@ async def set_metadata( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1847,7 +1869,7 @@ async def set_metadata( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1883,7 +1905,8 @@ async def get_access_policy( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.SignedIdentifiers :raises ~azure.core.exceptions.HttpResponseError: @@ -1930,7 +1953,7 @@ async def get_access_policy( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -1976,7 +1999,8 @@ async def set_access_policy( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2026,7 +2050,7 @@ async def set_access_policy( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2061,7 +2085,8 @@ async def get_statistics( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: ShareStats. The ShareStats is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ShareStats :raises ~azure.core.exceptions.HttpResponseError: @@ -2108,7 +2133,7 @@ async def get_statistics( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2155,7 +2180,8 @@ async def restore( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2197,7 +2223,7 @@ async def restore( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2235,14 +2261,14 @@ class DirectoryOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare.aio.AzureFileStorageClient`'s + :class:`~azure.storage.fileshare._generated.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: AzureFileStorageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + 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") @@ -2298,9 +2324,11 @@ async def create( # pylint: disable=too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -2312,7 +2340,7 @@ async def create( # pylint: disable=too-many-locals :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 + ~azure.storage.fileshare._generated.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 @@ -2368,7 +2396,7 @@ async def create( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2429,7 +2457,8 @@ async def get_properties( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -2474,7 +2503,7 @@ async def get_properties( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2532,7 +2561,8 @@ async def delete( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -2576,7 +2606,7 @@ async def delete( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2640,12 +2670,14 @@ async def set_properties( # pylint: disable=too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -2704,7 +2736,7 @@ async def set_properties( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2765,7 +2797,8 @@ async def set_metadata( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2807,7 +2840,7 @@ async def set_metadata( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2858,7 +2891,8 @@ async def list_files_and_directories_segment( :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] + :paramtype include: list[str or + ~azure.storage.fileshare._generated.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. @@ -2867,7 +2901,8 @@ async def list_files_and_directories_segment( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: ListFilesAndDirectoriesSegmentResponse. The ListFilesAndDirectoriesSegmentResponse is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ListFilesAndDirectoriesSegmentResponse @@ -2921,7 +2956,7 @@ async def list_files_and_directories_segment( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2977,7 +3012,8 @@ async def list_handles( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -3028,7 +3064,7 @@ async def list_handles( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3085,7 +3121,8 @@ async def force_close_handles( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3130,7 +3167,7 @@ async def force_close_handles( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3210,7 +3247,8 @@ async def rename( # pylint: disable=too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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. @@ -3222,7 +3260,8 @@ async def rename( # pylint: disable=too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3277,7 +3316,7 @@ async def rename( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3322,14 +3361,14 @@ class FileOperations: # pylint: disable=too-many-public-methods **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare.aio.AzureFileStorageClient`'s + :class:`~azure.storage.fileshare._generated.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: AzureFileStorageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + 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") @@ -3421,7 +3460,8 @@ async def create( # pylint: disable=too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 @@ -3429,7 +3469,8 @@ async def create( # pylint: disable=too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -3440,14 +3481,14 @@ async def create( # pylint: disable=too-many-locals :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 + :paramtype nfs_file_type: str or ~azure.storage.fileshare._generated.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 + ~azure.storage.fileshare._generated.models.FilePropertySemantics :keyword optional_content_length: Optional. Specifies the content length of the file. Default value is None. :paramtype optional_content_length: int @@ -3502,8 +3543,8 @@ async def create( # pylint: disable=too-many-locals content_md5=content_md5, file_property_semantics=file_property_semantics, optional_content_length=optional_content_length, - content_type=content_type, file_type=file_type, + content_type=content_type, version=self._config.version, content=_content, headers=_headers, @@ -3524,7 +3565,7 @@ async def create( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3598,7 +3639,8 @@ async def download( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :keyword structured_body_type: Optional. Used for structured get operations. Default value is None. :paramtype structured_body_type: str @@ -3652,7 +3694,7 @@ async def download( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3755,7 +3797,8 @@ async def get_properties( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: bool :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: @@ -3798,7 +3841,7 @@ async def get_properties( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3885,7 +3928,8 @@ async def delete( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3927,7 +3971,7 @@ async def delete( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4021,7 +4065,8 @@ async def set_http_headers( # pylint: disable=too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 @@ -4029,7 +4074,8 @@ async def set_http_headers( # pylint: disable=too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4096,7 +4142,7 @@ async def set_http_headers( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4159,7 +4205,8 @@ async def set_metadata( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4205,7 +4252,7 @@ async def set_metadata( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4250,7 +4297,8 @@ async def acquire_lease( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4298,7 +4346,7 @@ async def acquire_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4335,7 +4383,8 @@ async def release_lease( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4382,7 +4431,7 @@ async def release_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4423,7 +4472,8 @@ async def change_lease( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4471,7 +4521,7 @@ async def change_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4509,7 +4559,8 @@ async def break_lease( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4556,7 +4607,7 @@ async def break_lease( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4605,7 +4656,8 @@ async def upload_range( # pylint: disable=too-many-locals 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 + :paramtype file_range_write: str or + ~azure.storage.fileshare._generated.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. @@ -4618,12 +4670,14 @@ async def upload_range( # pylint: disable=too-many-locals :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 + :paramtype file_last_written_mode: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :keyword structured_body_type: Optional. Used for structured put operations. Default value is None. :paramtype structured_body_type: str @@ -4686,7 +4740,7 @@ async def upload_range( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4745,7 +4799,7 @@ async def upload_range_from_url( # pylint: disable=too-many-locals :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 + ~azure.storage.fileshare._generated.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. @@ -4769,7 +4823,8 @@ async def upload_range_from_url( # pylint: disable=too-many-locals :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 + :paramtype file_last_written_mode: str or + ~azure.storage.fileshare._generated.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 @@ -4777,7 +4832,8 @@ async def upload_range_from_url( # pylint: disable=too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4830,7 +4886,7 @@ async def upload_range_from_url( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4888,7 +4944,8 @@ async def get_range_list( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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. @@ -4944,7 +5001,7 @@ async def get_range_list( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5013,7 +5070,8 @@ async def start_copy( # pylint: disable=too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 @@ -5021,7 +5079,7 @@ async def start_copy( # pylint: disable=too-many-locals 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 + ~azure.storage.fileshare._generated.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 @@ -5047,7 +5105,8 @@ async def start_copy( # pylint: disable=too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -5058,10 +5117,11 @@ async def start_copy( # pylint: disable=too-many-locals :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 + :paramtype file_mode_copy_mode: str or ~azure.storage.fileshare._generated.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 + :paramtype file_owner_copy_mode: str or + ~azure.storage.fileshare._generated.models.OwnerCopyMode :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5121,7 +5181,7 @@ async def start_copy( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5167,7 +5227,8 @@ async def abort_copy( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5214,7 +5275,7 @@ async def abort_copy( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5258,7 +5319,8 @@ async def list_handles( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -5308,7 +5370,7 @@ async def list_handles( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5361,7 +5423,8 @@ async def force_close_handles( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5405,7 +5468,7 @@ async def force_close_handles( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5486,7 +5549,8 @@ async def rename( # pylint: disable=too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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. @@ -5500,7 +5564,8 @@ async def rename( # pylint: disable=too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5556,7 +5621,7 @@ async def rename( # pylint: disable=too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5631,7 +5696,8 @@ async def create_symbolic_link( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5678,7 +5744,7 @@ async def create_symbolic_link( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5728,7 +5794,8 @@ async def get_symbolic_link( specifies the share snapshot to query. 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5769,7 +5836,7 @@ async def get_symbolic_link( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5809,7 +5876,8 @@ async def create_hard_link( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5853,7 +5921,7 @@ async def create_hard_link( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) 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 ff607ac9e0f8..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 @@ -18,6 +18,7 @@ ClearRange, CorsRule, DirectoryItem, + Error, FileItem, FileProperty, FileRange, @@ -42,7 +43,6 @@ SignedIdentifier, SignedIdentifiers, SmbMultichannel, - StorageError, StorageServiceProperties, StringEncoded, UserDelegationKey, @@ -50,7 +50,7 @@ from ._enums import ( # type: ignore AccessRight, - CopyStatusType, + CopyStatus, DeleteSnapshotsOptionType, FileLastWrittenMode, FilePermissionFormat, @@ -80,6 +80,7 @@ "ClearRange", "CorsRule", "DirectoryItem", + "Error", "FileItem", "FileProperty", "FileRange", @@ -104,12 +105,11 @@ "SignedIdentifier", "SignedIdentifiers", "SmbMultichannel", - "StorageError", "StorageServiceProperties", "StringEncoded", "UserDelegationKey", "AccessRight", - "CopyStatusType", + "CopyStatus", "DeleteSnapshotsOptionType", "FileLastWrittenMode", "FilePermissionFormat", diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_enums.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_enums.py index 82435d2f6a98..a2732c2608da 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_enums.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/models/_enums.py @@ -21,7 +21,7 @@ class AccessRight(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Delete.""" -class CopyStatusType(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class CopyStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The copy status.""" PENDING = "pending" 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 index 4d376d7b5ceb..3724e6c1b762 100644 --- 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 @@ -261,6 +261,131 @@ 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._generated.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. @@ -346,8 +471,8 @@ class FileProperty(_Model): :vartype change_time: ~datetime.datetime :ivar last_modified: The last modified time. :vartype last_modified: ~datetime.datetime - :ivar etag: The ETag of the file. - :vartype etag: str + :ivar e_tag: The ETag of the file. + :vartype e_tag: str """ content_length: int = rest_field( @@ -362,39 +487,40 @@ class FileProperty(_Model): creation_time: Optional[datetime.datetime] = rest_field( name="creationTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + format="rfc7231", xml={"attribute": False, "name": "CreationTime", "text": False, "unwrapped": False}, ) """The creation time.""" last_access_time: Optional[datetime.datetime] = rest_field( name="lastAccessTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + format="rfc7231", xml={"attribute": False, "name": "LastAccessTime", "text": False, "unwrapped": False}, ) """The last access time.""" last_write_time: Optional[datetime.datetime] = rest_field( name="lastWriteTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + format="rfc7231", xml={"attribute": False, "name": "LastWriteTime", "text": False, "unwrapped": False}, ) """The last write time.""" change_time: Optional[datetime.datetime] = rest_field( name="changeTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + format="rfc7231", 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="rfc3339", + format="rfc7231", xml={"attribute": False, "name": "Last-Modified", "text": False, "unwrapped": False}, ) """The last modified time.""" - etag: Optional[str] = rest_field( + e_tag: Optional[str] = rest_field( + name="eTag", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Etag", "text": False, "unwrapped": False}, ) @@ -412,7 +538,7 @@ def __init__( last_write_time: Optional[datetime.datetime] = None, change_time: Optional[datetime.datetime] = None, last_modified: Optional[datetime.datetime] = None, - etag: Optional[str] = None, + e_tag: Optional[str] = None, ) -> None: ... @overload @@ -533,7 +659,7 @@ class HandleItem(_Model): :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] + :vartype access_right_list: list[str or ~azure.storage.fileshare._generated.models.AccessRight] """ handle_id: str = rest_field( @@ -580,7 +706,7 @@ class HandleItem(_Model): open_time: datetime.datetime = rest_field( name="openTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + 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). @@ -588,7 +714,7 @@ class HandleItem(_Model): last_reconnect_time: Optional[datetime.datetime] = rest_field( name="lastReconnectTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + format="rfc7231", xml={"attribute": False, "name": "LastReconnectTime", "text": False, "unwrapped": False}, ) """Time handle was last connected to (UTC).""" @@ -1221,7 +1347,7 @@ class SharePermission(_Model): Required. :vartype permission: str :ivar format: The permission format. Known values are: "Sddl" and "Binary". - :vartype format: str or ~azure.storage.fileshare.models.FilePermissionFormat + :vartype format: str or ~azure.storage.fileshare._generated.models.FilePermissionFormat """ permission: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -1255,8 +1381,8 @@ class SharePropertiesInternal(_Model): :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 e_tag: The ETag of the share. Required. + :vartype e_tag: str :ivar quota: The share quota. Required. :vartype quota: int :ivar provisioned_iops: The provisioned IOPS. @@ -1281,18 +1407,18 @@ class SharePropertiesInternal(_Model): :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 + :vartype lease_status: str or ~azure.storage.fileshare._generated.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 + :vartype lease_state: str or ~azure.storage.fileshare._generated.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 + :vartype lease_duration: str or ~azure.storage.fileshare._generated.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 + :vartype root_squash: str or ~azure.storage.fileshare._generated.models.ShareRootSquash :ivar enable_snapshot_virtual_directory_access: Whether snapshot virtual directory access is enabled. :vartype enable_snapshot_virtual_directory_access: bool @@ -1319,11 +1445,12 @@ class SharePropertiesInternal(_Model): last_modified: datetime.datetime = rest_field( name="lastModified", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + format="rfc7231", xml={"attribute": False, "name": "Last-Modified", "text": False, "unwrapped": False}, ) """The last modified time. Required.""" - etag: str = rest_field( + e_tag: str = rest_field( + name="eTag", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Etag", "text": False, "unwrapped": False}, ) @@ -1360,14 +1487,14 @@ class SharePropertiesInternal(_Model): next_allowed_quota_downgrade_time: Optional[datetime.datetime] = rest_field( name="nextAllowedQuotaDowngradeTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + 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="rfc3339", + format="rfc7231", xml={"attribute": False, "name": "DeletedTime", "text": False, "unwrapped": False}, ) """The deleted time.""" @@ -1386,7 +1513,7 @@ class SharePropertiesInternal(_Model): access_tier_change_time: Optional[datetime.datetime] = rest_field( name="accessTierChangeTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + format="rfc7231", xml={"attribute": False, "name": "AccessTierChangeTime", "text": False, "unwrapped": False}, ) """The access tier change time.""" @@ -1467,14 +1594,14 @@ class SharePropertiesInternal(_Model): next_allowed_provisioned_iops_downgrade_time: Optional[datetime.datetime] = rest_field( name="nextAllowedProvisionedIopsDowngradeTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", + 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="rfc3339", + format="rfc7231", xml={ "attribute": False, "name": "NextAllowedProvisionedBandwidthDowngradeTime", @@ -1497,7 +1624,7 @@ def __init__( # pylint: disable=too-many-locals self, *, last_modified: datetime.datetime, - etag: str, + e_tag: str, quota: int, provisioned_iops: Optional[int] = None, provisioned_ingress_m_bps: Optional[int] = None, @@ -1805,131 +1932,6 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class StorageError(_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 StorageServiceProperties(_Model): """Storage service properties. @@ -2040,9 +2042,9 @@ class UserDelegationKey(_Model): :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 + :vartype signed_start: str :ivar signed_expiry: The date-time the key expires. Required. - :vartype signed_expiry: ~datetime.datetime + :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. @@ -2066,17 +2068,15 @@ class UserDelegationKey(_Model): xml={"attribute": False, "name": "SignedTid", "text": False, "unwrapped": False}, ) """The Azure Active Directory tenant ID in GUID format. Required.""" - signed_start: datetime.datetime = rest_field( + signed_start: str = rest_field( name="signedStart", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", xml={"attribute": False, "name": "SignedStart", "text": False, "unwrapped": False}, ) """The date-time the key is active. Required.""" - signed_expiry: datetime.datetime = rest_field( + signed_expiry: str = rest_field( name="signedExpiry", visibility=["read", "create", "update", "delete", "query"], - format="rfc3339", xml={"attribute": False, "name": "SignedExpiry", "text": False, "unwrapped": False}, ) """The date-time the key expires. Required.""" @@ -2112,8 +2112,8 @@ def __init__( *, signed_oid: str, signed_tid: str, - signed_start: datetime.datetime, - signed_expiry: datetime.datetime, + signed_start: str, + signed_expiry: str, signed_service: str, signed_version: str, value: str, 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 index 1dd2dfe37d04..9b212610bf8c 100644 --- 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 @@ -28,7 +28,7 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models -from .._configuration import AzureFileStorageClientConfiguration +from .._configuration import FileClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize, _deserialize_xml, _failsafe_deserialize_xml, _get_element from .._utils.serialization import Deserializer, Serializer @@ -60,8 +60,7 @@ def build_service_set_properties_request( # 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["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") @@ -154,8 +153,7 @@ def build_service_get_user_delegation_key_request( # pylint: disable=name-too-l _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _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") @@ -708,7 +706,7 @@ def build_share_set_access_policy_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL _url = "?restype=share&comp=acl" @@ -1217,7 +1215,7 @@ def build_directory_rename_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_create_request( # pylint: disable=too-many-locals +def build_file_create_request( # pylint: disable=too-many-locals,too-many-statements,too-many-branches *, content_length: int, timeout: Optional[int] = None, @@ -1250,11 +1248,11 @@ def build_file_create_request( # pylint: disable=too-many-locals _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") 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-04-06")) # Construct URL - _url = "/" + _url = "" # Construct parameters if timeout is not None: @@ -1342,7 +1340,7 @@ def build_file_download_request( accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "/" + _url = "" # Construct parameters if timeout is not None: @@ -1351,7 +1349,7 @@ def build_file_download_request( # 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") + _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" @@ -1383,7 +1381,7 @@ def build_file_get_properties_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "/" + _url = "" # Construct parameters if sharesnapshot is not None: @@ -1416,7 +1414,7 @@ def build_file_delete_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "/" + _url = "" # Construct parameters if timeout is not None: @@ -1708,7 +1706,7 @@ def build_file_upload_range_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL _url = "?comp=range" @@ -1721,7 +1719,7 @@ def build_file_upload_range_request( _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-range"] = _SERIALIZER.header("range", range, "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: @@ -1778,7 +1776,7 @@ def build_file_upload_range_from_url_request( # Construct headers _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["x-ms-range"] = _SERIALIZER.header("range", range, "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") @@ -1848,7 +1846,7 @@ def build_file_get_range_list_request( # 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") + _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: @@ -1893,7 +1891,7 @@ def build_file_start_copy_request( # pylint: disable=too-many-locals version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-04-06")) # Construct URL - _url = "/" + _url = "" # Construct parameters if timeout is not None: @@ -2256,14 +2254,14 @@ class ServiceOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare.AzureFileStorageClient`'s + :class:`~azure.storage.fileshare._generated.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: AzureFileStorageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + 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") @@ -2285,7 +2283,8 @@ def set_properties( # pylint: disable=inconsistent-return-statements :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2330,7 +2329,7 @@ def set_properties( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2360,7 +2359,8 @@ def get_properties( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: StorageServiceProperties. The StorageServiceProperties is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.StorageServiceProperties @@ -2407,7 +2407,7 @@ def get_properties( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2457,10 +2457,12 @@ def list_shares_segment( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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] + :paramtype include: list[str or + ~azure.storage.fileshare._generated.models.ListSharesIncludeType] :return: ListSharesResponse. The ListSharesResponse is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ListSharesResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -2510,7 +2512,7 @@ def list_shares_segment( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2594,7 +2596,7 @@ def get_user_delegation_key( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2625,14 +2627,14 @@ class ShareOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare.AzureFileStorageClient`'s + :class:`~azure.storage.fileshare._generated.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: AzureFileStorageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + 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") @@ -2667,12 +2669,12 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals :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 + :paramtype access_tier: str or ~azure.storage.fileshare._generated.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 + :paramtype root_squash: str or ~azure.storage.fileshare._generated.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 @@ -2688,7 +2690,8 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :keyword share_provisioned_iops: Optional. Specifies the provisioned IOPS of the share. Default value is None. :paramtype share_provisioned_iops: int @@ -2749,7 +2752,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2799,7 +2802,8 @@ def get_properties( # pylint: disable=inconsistent-return-statements :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -2844,7 +2848,7 @@ def get_properties( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -2941,9 +2945,11 @@ def delete( # pylint: disable=inconsistent-return-statements :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 + :paramtype delete_snapshots: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -2989,7 +2995,7 @@ def delete( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3039,7 +3045,8 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3084,7 +3091,7 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3124,7 +3131,8 @@ def release_lease( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3168,7 +3176,7 @@ def release_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3212,7 +3220,8 @@ def change_lease( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3257,7 +3266,7 @@ def change_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3297,7 +3306,8 @@ def renew_lease( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3341,7 +3351,7 @@ def renew_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3391,7 +3401,8 @@ def break_lease( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3436,7 +3447,7 @@ def break_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3472,7 +3483,8 @@ def create_snapshot( # pylint: disable=inconsistent-return-statements :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3513,7 +3525,7 @@ def create_snapshot( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3553,7 +3565,8 @@ def create_permission( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3580,7 +3593,8 @@ def create_permission( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3607,7 +3621,8 @@ def create_permission( :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3632,7 +3647,8 @@ def create_permission( # pylint: disable=inconsistent-return-statements :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3682,7 +3698,7 @@ def create_permission( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3722,9 +3738,11 @@ def get_permission( :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: SharePermission. The SharePermission is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.SharePermission :raises ~azure.core.exceptions.HttpResponseError: @@ -3772,7 +3790,7 @@ def get_permission( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3823,13 +3841,13 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l :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 + :paramtype access_tier: str or ~azure.storage.fileshare._generated.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 + :paramtype root_squash: str or ~azure.storage.fileshare._generated.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 @@ -3845,7 +3863,8 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :keyword share_provisioned_iops: Optional. Specifies the provisioned number of input/output operations per second (IOPS) of the share. Default value is None. :paramtype share_provisioned_iops: int @@ -3905,7 +3924,7 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -3965,7 +3984,8 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4007,7 +4027,7 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4043,7 +4063,8 @@ def get_access_policy( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.SignedIdentifiers :raises ~azure.core.exceptions.HttpResponseError: @@ -4090,7 +4111,7 @@ def get_access_policy( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4136,7 +4157,8 @@ def set_access_policy( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4186,7 +4208,7 @@ def set_access_policy( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4221,7 +4243,8 @@ def get_statistics( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: ShareStats. The ShareStats is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ShareStats :raises ~azure.core.exceptions.HttpResponseError: @@ -4268,7 +4291,7 @@ def get_statistics( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4315,7 +4338,8 @@ def restore( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4357,7 +4381,7 @@ def restore( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4395,14 +4419,14 @@ class DirectoryOperations: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare.AzureFileStorageClient`'s + :class:`~azure.storage.fileshare._generated.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: AzureFileStorageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + 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") @@ -4458,9 +4482,11 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4472,7 +4498,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals :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 + ~azure.storage.fileshare._generated.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 @@ -4528,7 +4554,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4589,7 +4615,8 @@ def get_properties( # pylint: disable=inconsistent-return-statements :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4634,7 +4661,7 @@ def get_properties( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4692,7 +4719,8 @@ def delete( # pylint: disable=inconsistent-return-statements :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4736,7 +4764,7 @@ def delete( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4800,12 +4828,14 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -4864,7 +4894,7 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -4925,7 +4955,8 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4967,7 +4998,7 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5018,7 +5049,8 @@ def list_files_and_directories_segment( :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] + :paramtype include: list[str or + ~azure.storage.fileshare._generated.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. @@ -5027,7 +5059,8 @@ def list_files_and_directories_segment( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: ListFilesAndDirectoriesSegmentResponse. The ListFilesAndDirectoriesSegmentResponse is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ListFilesAndDirectoriesSegmentResponse @@ -5081,7 +5114,7 @@ def list_files_and_directories_segment( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5137,7 +5170,8 @@ def list_handles( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -5188,7 +5222,7 @@ def list_handles( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5245,7 +5279,8 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5290,7 +5325,7 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5370,7 +5405,8 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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. @@ -5382,7 +5418,8 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5437,7 +5474,7 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5482,14 +5519,14 @@ class FileOperations: # pylint: disable=too-many-public-methods **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare.AzureFileStorageClient`'s + :class:`~azure.storage.fileshare._generated.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: AzureFileStorageClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + 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") @@ -5581,7 +5618,8 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 @@ -5589,7 +5627,8 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -5600,14 +5639,14 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals :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 + :paramtype nfs_file_type: str or ~azure.storage.fileshare._generated.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 + ~azure.storage.fileshare._generated.models.FilePropertySemantics :keyword optional_content_length: Optional. Specifies the content length of the file. Default value is None. :paramtype optional_content_length: int @@ -5662,8 +5701,8 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals content_md5=content_md5, file_property_semantics=file_property_semantics, optional_content_length=optional_content_length, - content_type=content_type, file_type=file_type, + content_type=content_type, version=self._config.version, content=_content, headers=_headers, @@ -5684,7 +5723,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5758,7 +5797,8 @@ def download( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :keyword structured_body_type: Optional. Used for structured get operations. Default value is None. :paramtype structured_body_type: str @@ -5812,7 +5852,7 @@ def download( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -5915,7 +5955,8 @@ def get_properties( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: bool :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: @@ -5958,7 +5999,7 @@ def get_properties( 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6045,7 +6086,8 @@ def delete( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6087,7 +6129,7 @@ def delete( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6181,7 +6223,8 @@ def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 @@ -6189,7 +6232,8 @@ def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -6256,7 +6300,7 @@ def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6319,7 +6363,8 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -6365,7 +6410,7 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6410,7 +6455,8 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -6458,7 +6504,7 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6495,7 +6541,8 @@ def release_lease( # pylint: disable=inconsistent-return-statements :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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -6542,7 +6589,7 @@ def release_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6583,7 +6630,8 @@ def change_lease( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -6631,7 +6679,7 @@ def change_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6669,7 +6717,8 @@ def break_lease( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -6716,7 +6765,7 @@ def break_lease( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6765,7 +6814,8 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc 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 + :paramtype file_range_write: str or + ~azure.storage.fileshare._generated.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. @@ -6778,12 +6828,14 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc :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 + :paramtype file_last_written_mode: str or + ~azure.storage.fileshare._generated.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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :keyword structured_body_type: Optional. Used for structured put operations. Default value is None. :paramtype structured_body_type: str @@ -6846,7 +6898,7 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -6905,7 +6957,7 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too :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 + ~azure.storage.fileshare._generated.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. @@ -6929,7 +6981,8 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too :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 + :paramtype file_last_written_mode: str or + ~azure.storage.fileshare._generated.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 @@ -6937,7 +6990,8 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6990,7 +7044,7 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7048,7 +7102,8 @@ def get_range_list( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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. @@ -7104,7 +7159,7 @@ def get_range_list( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7173,7 +7228,8 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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 @@ -7181,7 +7237,7 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local 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 + ~azure.storage.fileshare._generated.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 @@ -7207,7 +7263,8 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.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 @@ -7218,10 +7275,11 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local :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 + :paramtype file_mode_copy_mode: str or ~azure.storage.fileshare._generated.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 + :paramtype file_owner_copy_mode: str or + ~azure.storage.fileshare._generated.models.OwnerCopyMode :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7281,7 +7339,7 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7327,7 +7385,8 @@ def abort_copy( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7374,7 +7433,7 @@ def abort_copy( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7418,7 +7477,8 @@ def list_handles( 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -7468,7 +7528,7 @@ def list_handles( pass map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize_xml( - _models.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7521,7 +7581,8 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7565,7 +7626,7 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7646,7 +7707,8 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals :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 + :paramtype file_permission_format: str or + ~azure.storage.fileshare._generated.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. @@ -7660,7 +7722,8 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7716,7 +7779,7 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7791,7 +7854,8 @@ def create_symbolic_link( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7838,7 +7902,7 @@ def create_symbolic_link( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7888,7 +7952,8 @@ def get_symbolic_link( # pylint: disable=inconsistent-return-statements specifies the share snapshot to query. 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7929,7 +7994,7 @@ def get_symbolic_link( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) @@ -7969,7 +8034,8 @@ def create_hard_link( # pylint: disable=inconsistent-return-statements 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 + :paramtype file_request_intent: str or + ~azure.storage.fileshare._generated.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -8013,7 +8079,7 @@ def create_hard_link( # pylint: disable=inconsistent-return-statements 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.StorageError, + _models.Error, response, ) raise HttpResponseError(response=response, model=error) 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 0deed5571313..45e88b1a2878 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 @@ -36,6 +36,7 @@ "build_file_start_copy_request", ] + def _fix_trailing_slash(build_fn): """Wrap a build_*_request function to strip the trailing slash from _url = "/".""" @@ -59,4 +60,4 @@ def patch_sdk(): """ for fn_name in _TRAILING_SLASH_FUNCTIONS: original = getattr(_operations, fn_name) - setattr(_operations, fn_name, _fix_trailing_slash(original)) \ No newline at end of file + setattr(_operations, fn_name, _fix_trailing_slash(original)) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/py.typed b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/py.typed new file mode 100644 index 000000000000..e5aff4f83af8 --- /dev/null +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/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/azure/storage/fileshare/_models.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_models.py index f0b1fe411114..9d9f6b6f22db 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 @@ -307,7 +307,9 @@ class ShareNfsSettings(GeneratedShareNfsSettings): encryption_in_transit: NfsEncryptionInTransit """Sets the encryption in transit settings.""" - def __init__(self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any) -> None: # pylint: disable=unused-argument + def __init__( + self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any + ) -> None: # pylint: disable=unused-argument self._data = {} self.encryption_in_transit = encryption_in_transit @@ -674,7 +676,7 @@ def _from_generated(cls, generated): props = cls() props.name = generated.name props.last_modified = generated.properties.last_modified - props.etag = generated.properties.etag + props.etag = generated.properties.e_tag props.quota = generated.properties.quota props.access_tier = generated.properties.access_tier props.next_allowed_quota_downgrade_time = generated.properties.next_allowed_quota_downgrade_time @@ -1072,7 +1074,7 @@ def _from_generated(cls, generated): props.last_access_time = generated.properties.last_access_time props.last_write_time = generated.properties.last_write_time props.change_time = generated.properties.change_time - props.etag = generated.properties.etag + props.etag = generated.properties.e_tag props.permission_key = generated.permission_key return props @@ -1146,7 +1148,9 @@ def _extract_data_cb(self, get_next_return): 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: disable=protected-access + [ + FileProperties._from_generated(i) for i in self._response.segment.file_items + ] # pylint: disable=protected-access ) return self._response.next_marker or None, self.current_page @@ -1332,7 +1336,7 @@ def _from_generated(cls, generated): props = cls() props.name = unquote(generated.name.content) if generated.name.encoded else generated.name.content props.file_id = generated.file_id - props.etag = generated.properties.etag + props.etag = generated.properties.e_tag props.file_attributes = generated.attributes props.last_modified = generated.properties.last_modified props.creation_time = generated.properties.creation_time 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 7323a1f35fa5..5dfe4d142794 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 @@ -11,8 +11,7 @@ _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" + "Size of file_permission is too large. file_permission should be <=8KB, else " "please use file_permission_key" ) 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 ce73bee1fef6..bec1bc935b9e 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 @@ -16,7 +16,7 @@ from ._deserialize import deserialize_permission, deserialize_share_properties from ._directory_client import ShareDirectoryClient from ._file_client import ShareFileClient -from ._generated import AzureFileStorageClient as AzureFileStorage +from ._generated import FileClient as AzureFileStorage from ._generated.models import DeleteSnapshotsOptionType, ShareStats, SignedIdentifier, SignedIdentifiers from ._lease import ShareLeaseClient from ._models import ShareProtocols 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 f0914d2a585a..c8886f591834 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 @@ -14,7 +14,7 @@ from azure.core.paging import ItemPaged from azure.core.pipeline import Pipeline from azure.core.tracing.decorator import distributed_trace -from ._generated import AzureFileStorageClient as AzureFileStorage +from ._generated import FileClient as AzureFileStorage from ._generated.models import KeyInfo, StorageServiceProperties from ._models import ( CorsRule, 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 cc3198a07398..3a920ac6baac 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 @@ -201,14 +201,29 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p raise error from exc +def _extract_text(value): + """Extract text from a value that may be an XML Element.""" + if isinstance(value, Element): + return value.text + return value + + def parse_to_internal_user_delegation_key(service_user_delegation_key): internal_user_delegation_key = UserDelegationKey() - 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_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 + internal_user_delegation_key.signed_oid = _extract_text(service_user_delegation_key.signed_oid) + internal_user_delegation_key.signed_tid = _extract_text(service_user_delegation_key.signed_tid) + internal_user_delegation_key.signed_delegated_user_tid = _extract_text( + service_user_delegation_key.signed_delegated_user_tid + ) + signed_start = _extract_text(service_user_delegation_key.signed_start) + internal_user_delegation_key.signed_start = ( + signed_start if isinstance(signed_start, str) else _to_utc_datetime(signed_start) + ) + signed_expiry = _extract_text(service_user_delegation_key.signed_expiry) + internal_user_delegation_key.signed_expiry = ( + signed_expiry if isinstance(signed_expiry, str) else _to_utc_datetime(signed_expiry) + ) + internal_user_delegation_key.signed_service = _extract_text(service_user_delegation_key.signed_service) + internal_user_delegation_key.signed_version = _extract_text(service_user_delegation_key.signed_version) + internal_user_delegation_key.value = _extract_text(service_user_delegation_key.value) return internal_user_delegation_key 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 20200954f3f1..b17452ced1af 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 @@ -21,7 +21,7 @@ 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 AzureFileStorageClient as AzureFileStorage +from .._generated.aio import FileClient as AzureFileStorage from .._parser import _datetime_to_str, _get_file_permission, _parse_snapshot from .._serialize import get_api_version, get_dest_access_conditions, get_rename_smb_properties from .._shared.base_client import parse_query, StorageAccountHostsMixin 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 07f15fd7f030..b1e113fc0163 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 @@ -43,7 +43,7 @@ _parse_url, _upload_range_from_url_options, ) -from .._generated.aio import AzureFileStorageClient as AzureFileStorage +from .._generated.aio import FileClient as AzureFileStorage from .._parser import _datetime_to_str, _get_file_permission, _parse_snapshot from .._serialize import ( get_access_conditions, 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 e8668a6c88b8..c84ad4861069 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 @@ -206,6 +206,8 @@ async def _extract_data_cb(self, get_next_return): 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: disable=protected-access + [ + FileProperties._from_generated(i) for i in self._response.segment.file_items + ] # pylint: disable=protected-access ) 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 1e8f410e4f61..65737b60773c 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 @@ -17,7 +17,7 @@ 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 AzureFileStorageClient as AzureFileStorage +from .._generated.aio import FileClient as AzureFileStorage from .._generated.models import DeleteSnapshotsOptionType, ShareStats, SignedIdentifier, SignedIdentifiers from .._models import ShareProtocols from .._parser import _parse_snapshot 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 24a3b2daf8a5..c591af31bc97 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 @@ -16,7 +16,7 @@ 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 AzureFileStorageClient as AzureFileStorage +from .._generated.aio import FileClient as AzureFileStorage from .._generated.models import KeyInfo, StorageServiceProperties from .._models import CorsRule, service_properties_deserialize, ShareProperties from .._serialize import get_api_version diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index a9a3c3d0ce7f..f9ecd8119979 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -43,7 +43,7 @@ dynamic = [ repository = "https://github.com/Azure/azure-sdk-for-python" [tool.setuptools.dynamic] -version = {attr = "azure.storage.fileshare._version.VERSION"} +version = {attr = "azure.storage.fileshare._generated._version.VERSION"} readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} [tool.setuptools.packages.find] @@ -55,6 +55,7 @@ exclude = [ "doc*", "azure", "azure.storage", + "azure.storage.fileshare", ] [tool.setuptools.package-data] 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 a2c056d3a311..000000000000 --- a/sdk/storage/azure-storage-file-share/setup.py +++ /dev/null @@ -1,75 +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/test_helpers.py b/sdk/storage/azure-storage-file-share/tests/test_helpers.py index 8d769ef28c26..cd4e59c81d99 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_helpers.py +++ b/sdk/storage/azure-storage-file-share/tests/test_helpers.py @@ -32,13 +32,16 @@ def assert_complete(self): 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 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 a64d0b75edf6..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 @@ -51,13 +51,16 @@ async def read(self, size: int = -1) -> bytes: 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 diff --git a/sdk/storage/azure-storage-file-share/tsp-location.yaml b/sdk/storage/azure-storage-file-share/tsp-location.yaml index 7cb450202a52..1a710edd36c7 100644 --- a/sdk/storage/azure-storage-file-share/tsp-location.yaml +++ b/sdk/storage/azure-storage-file-share/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/storage/data-plane/FileStorage -commit: b760190f490001759361c8e7b59d8b5b191dc12d -repo: Azure/azure-rest-api-specs -additionalDirectories: [] +commit: +repo: +additionalDirectories: From 36567386161ca4608a3e4f11a7e9ed3a0dbc7867 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 26 Mar 2026 12:24:25 -0700 Subject: [PATCH 08/45] prpoject version --- sdk/storage/azure-storage-file-share/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index f9ecd8119979..ee14eb19fac3 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -43,7 +43,7 @@ dynamic = [ repository = "https://github.com/Azure/azure-sdk-for-python" [tool.setuptools.dynamic] -version = {attr = "azure.storage.fileshare._generated._version.VERSION"} +version = {attr = "azure.storage.fileshare._version.VERSION"} readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} [tool.setuptools.packages.find] From acf7f305c8ec863c395959f767610912c4484ab7 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 26 Mar 2026 12:26:44 -0700 Subject: [PATCH 09/45] remove --- .../azure-storage-file-share/debug_svc.py | 36 ------------------- 1 file changed, 36 deletions(-) delete mode 100644 sdk/storage/azure-storage-file-share/debug_svc.py diff --git a/sdk/storage/azure-storage-file-share/debug_svc.py b/sdk/storage/azure-storage-file-share/debug_svc.py deleted file mode 100644 index b40354b062ba..000000000000 --- a/sdk/storage/azure-storage-file-share/debug_svc.py +++ /dev/null @@ -1,36 +0,0 @@ -import sys -import azure.storage.fileshare._models as models - -orig_deserialize = models.service_properties_deserialize - - -def debug_deserialize(generated): - print(f"DEBUG generated type: {type(generated)}", file=sys.stderr) - if hasattr(generated, "hour_metrics"): - hm = generated.hour_metrics - print(f"DEBUG hour_metrics type: {type(hm)}", file=sys.stderr) - if hm: - data = getattr(hm, "_data", "NO _data") - print(f"DEBUG hm._data: {data}", file=sys.stderr) - rp = getattr(hm, "retention_policy", "NO retention_policy") - print(f"DEBUG retention_policy: {type(rp)} = {rp}", file=sys.stderr) - return orig_deserialize(generated) - - -models.service_properties_deserialize = debug_deserialize -import azure.storage.fileshare._share_service_client as ssc - -ssc.service_properties_deserialize = debug_deserialize - -import pytest - -pytest.main( - [ - "-x", - "tests/test_file_service_properties.py::TestFileServiceProperties::test_file_service_properties", - "-q", - "--tb=short", - "--no-header", - "-s", - ] -) From 1dc62f402dcd5e1e9be2010a3cea2faeb1870b75 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 26 Mar 2026 12:28:13 -0700 Subject: [PATCH 10/45] patch remove fix --- .../fileshare/_generated/operations/_patch.py | 43 ------------------- 1 file changed, 43 deletions(-) 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 45e88b1a2878..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 @@ -7,50 +7,10 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import functools - -from . import _operations - __all__: list[str] = [] # Add all objects you want publicly available to users at this package level -# --------------------------------------------------------------------------- -# Emitter bug fixes applied via patch_sdk() -# -# 1. Trailing slash: The emitter generates _url = "/" for @route("") which -# creates a trailing slash when combined with the base URL. Fix: change -# _url from "/" to "" in the affected build_*_request functions. -# -# 2. Missing Accept header: Operations using StorageOperationNoBody (no -# response body) don't get an Accept header generated, even though error -# responses are XML. Fix: set Accept: application/xml as the default. -# --------------------------------------------------------------------------- - -# Build functions that generate _url = "/" (trailing slash bug) -_TRAILING_SLASH_FUNCTIONS = [ - "build_file_create_request", - "build_file_download_request", - "build_file_get_properties_request", - "build_file_delete_request", - "build_file_start_copy_request", -] - - -def _fix_trailing_slash(build_fn): - """Wrap a build_*_request function to strip the trailing slash from _url = "/".""" - - @functools.wraps(build_fn) - def wrapper(*args, **kwargs): - request = build_fn(*args, **kwargs) - url = request.url - if url == "/" or url.startswith("/?"): - request.url = url[1:] # Strip leading "/" - return request - - return wrapper - - def patch_sdk(): """Do not remove from this file. @@ -58,6 +18,3 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ - for fn_name in _TRAILING_SLASH_FUNCTIONS: - original = getattr(_operations, fn_name) - setattr(_operations, fn_name, _fix_trailing_slash(original)) From 3e9b4d87670afacf72619575d266e966a8e9e885 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 26 Mar 2026 12:34:34 -0700 Subject: [PATCH 11/45] fix client helpers --- .../storage/fileshare/_client_helpers.py | 33 ------------------- .../storage/fileshare/_directory_client.py | 4 +-- .../azure/storage/fileshare/_file_client.py | 4 +-- .../azure/storage/fileshare/_parser.py | 19 +++++++++++ .../azure/storage/fileshare/_share_client.py | 4 +-- .../fileshare/_share_service_client.py | 3 +- .../fileshare/aio/_directory_client_async.py | 4 +-- .../fileshare/aio/_file_client_async.py | 4 +-- .../fileshare/aio/_share_client_async.py | 4 +-- .../aio/_share_service_client_async.py | 3 +- 10 files changed, 27 insertions(+), 55 deletions(-) delete mode 100644 sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py deleted file mode 100644 index 75f8f87f6fc0..000000000000 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_client_helpers.py +++ /dev/null @@ -1,33 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -"""Helpers for the Azure File Share convenience layer clients.""" - - -class _NoOpCredential: - """No-op credential for the generated client when auth is handled by the convenience layer pipeline.""" - - def get_token(self, *args, **kwargs): - raise RuntimeError("This credential should not be used to get tokens directly.") - - -def _strip_snapshot_from_url(url): - """Strip sharesnapshot and snapshot query params from 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=") and not part.startswith("snapshot=") - ) - return f"{base}?{filtered}" if filtered else base 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 8fb87b57ad96..879b4568b04f 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 @@ -22,10 +22,9 @@ from ._file_client import ShareFileClient 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 ._client_helpers import _NoOpCredential, _strip_snapshot_from_url from ._shared.request_handlers import add_metadata_headers from ._shared.response_handlers import process_storage_error, return_response_headers @@ -131,7 +130,6 @@ def __init__( self.file_request_intent = token_intent self._client = AzureFileStorage( url=_strip_snapshot_from_url(self.url), - credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) 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 fcf20f28cdbb..cacdc63cca78 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 @@ -28,7 +28,7 @@ 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, @@ -38,7 +38,6 @@ get_source_access_conditions, ) from ._shared.base_client import StorageAccountHostsMixin, parse_connection_str, parse_query -from ._client_helpers import _NoOpCredential, _strip_snapshot_from_url from ._shared.constants import DEFAULT_MAX_CONCURRENCY from ._shared.request_handlers import add_metadata_headers, get_length from ._shared.response_handlers import return_response_headers, process_storage_error @@ -194,7 +193,6 @@ def __init__( self.file_request_intent = token_intent self._client = AzureFileStorage( url=_strip_snapshot_from_url(self.url), - credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) 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 5dfe4d142794..655bd98f1f39 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 @@ -58,3 +58,22 @@ def _parse_snapshot( if isinstance(snapshot, Dict): 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/_share_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_share_client.py index bec1bc935b9e..43921801612d 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 @@ -20,11 +20,10 @@ 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 ._shared.base_client import parse_connection_str, parse_query, StorageAccountHostsMixin, TransportWrapper -from ._client_helpers import _NoOpCredential, _strip_snapshot_from_url 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 @@ -119,7 +118,6 @@ def __init__( self.file_request_intent = token_intent self._client = AzureFileStorage( url=_strip_snapshot_from_url(self.url), - credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) 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 c8886f591834..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 @@ -22,11 +22,11 @@ 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 from ._shared.base_client import StorageAccountHostsMixin, TransportWrapper, parse_connection_str, parse_query -from ._client_helpers import _NoOpCredential, _strip_snapshot_from_url from ._shared.parser import _to_utc_datetime from ._shared.response_handlers import parse_to_internal_user_delegation_key, process_storage_error @@ -128,7 +128,6 @@ def __init__( self.file_request_intent = token_intent self._client = AzureFileStorage( url=_strip_snapshot_from_url(self.url), - credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) 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 b17452ced1af..20dc05137024 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 @@ -22,11 +22,10 @@ from .._deserialize import deserialize_directory_properties 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 +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 -from .._client_helpers import _NoOpCredential, _strip_snapshot_from_url from .._shared.policies_async import ExponentialRetry from .._shared.request_handlers import add_metadata_headers from .._shared.response_handlers import process_storage_error, return_response_headers @@ -140,7 +139,6 @@ def __init__( self.file_request_intent = token_intent self._client = AzureFileStorage( url=_strip_snapshot_from_url(self.url), - credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) 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 b1e113fc0163..bd311338cdc1 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 @@ -44,7 +44,7 @@ _upload_range_from_url_options, ) from .._generated.aio import FileClient as AzureFileStorage -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, @@ -55,7 +55,6 @@ ) from .._shared.base_client import StorageAccountHostsMixin, parse_query from .._shared.base_client_async import AsyncStorageAccountHostsMixin, parse_connection_str -from .._client_helpers import _NoOpCredential, _strip_snapshot_from_url from .._shared.constants import DEFAULT_MAX_CONCURRENCY from .._shared.policies_async import ExponentialRetry from .._shared.request_handlers import add_metadata_headers, get_length @@ -220,7 +219,6 @@ def __init__( self.file_request_intent = token_intent self._client = AzureFileStorage( url=_strip_snapshot_from_url(self.url), - credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) 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 65737b60773c..7c9f69632ea0 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 @@ -20,12 +20,11 @@ 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 .._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 .._client_helpers import _NoOpCredential, _strip_snapshot_from_url 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 .._serialize import get_access_conditions, get_api_version @@ -128,7 +127,6 @@ def __init__( self.file_request_intent = token_intent self._client = AzureFileStorage( url=_strip_snapshot_from_url(self.url), - credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) 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 c591af31bc97..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 @@ -19,11 +19,11 @@ 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 from .._shared.base_client_async import AsyncStorageAccountHostsMixin, AsyncTransportWrapper, parse_connection_str -from .._client_helpers import _NoOpCredential, _strip_snapshot_from_url from .._shared.parser import _to_utc_datetime from .._shared.policies_async import ExponentialRetry from .._shared.response_handlers import parse_to_internal_user_delegation_key, process_storage_error @@ -134,7 +134,6 @@ def __init__( self.file_request_intent = token_intent self._client = AzureFileStorage( url=_strip_snapshot_from_url(self.url), - credential=_NoOpCredential(), version=get_api_version(kwargs), pipeline=self._pipeline, ) From 0412403028be4cb0dade98178765d9a532d6d218 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 27 Mar 2026 08:18:53 -0700 Subject: [PATCH 12/45] regen --- .../azure/storage/fileshare/_parser.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 655bd98f1f39..6e92e0bd54c9 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 @@ -73,7 +73,5 @@ def _strip_snapshot_from_url(url: str) -> 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=")) - ) + filtered = "&".join(part for part in qs.split("&") if not part.startswith(("sharesnapshot=", "snapshot="))) return f"{base}?{filtered}" if filtered else base From f317d7718c862e958b6fa2c5d0e55cab2d955a2e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 27 Mar 2026 12:32:58 -0700 Subject: [PATCH 13/45] pyproject --- sdk/storage/azure-storage-file-share/pyproject.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index ee14eb19fac3..a9a3c3d0ce7f 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -55,7 +55,6 @@ exclude = [ "doc*", "azure", "azure.storage", - "azure.storage.fileshare", ] [tool.setuptools.package-data] From 001090dc8bfe2e35cdad0666cbbc11deb4e6c17e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 30 Mar 2026 10:54:02 -0700 Subject: [PATCH 14/45] pylint --- .../azure/storage/fileshare/_models.py | 9 +++++---- .../azure/storage/fileshare/_parser.py | 3 ++- .../azure/storage/fileshare/_shared/response_handlers.py | 7 ++++++- .../azure/storage/fileshare/aio/_models.py | 5 +++-- 4 files changed, 16 insertions(+), 8 deletions(-) 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 9d9f6b6f22db..31f6ce0f520a 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 @@ -308,8 +308,8 @@ class ShareNfsSettings(GeneratedShareNfsSettings): """Sets the encryption in transit settings.""" def __init__( - self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any - ) -> None: # pylint: disable=unused-argument + self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any # pylint: disable=unused-argument + ) -> None: self._data = {} self.encryption_in_transit = encryption_in_transit @@ -1149,8 +1149,9 @@ def _extract_data_cb(self, get_next_return): ] self.current_page.extend( [ - FileProperties._from_generated(i) for i in self._response.segment.file_items - ] # pylint: disable=protected-access + 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/_parser.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_parser.py index 6e92e0bd54c9..a6705a794995 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 @@ -11,7 +11,8 @@ _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" + "Size of file_permission is too large. file_permission should be <=8KB, else " + "please use file_permission_key" ) 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 3a920ac6baac..16d041bb8c33 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 @@ -202,7 +202,12 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p def _extract_text(value): - """Extract text from a value that may be an XML Element.""" + """Extract text from a value that may be an XML Element. + + :param Any value: The value to extract text from. + :returns: The text content if value is an XML Element, otherwise the value itself. + :rtype: str or None + """ if isinstance(value, Element): return value.text return value 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 c84ad4861069..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 @@ -207,7 +207,8 @@ async def _extract_data_cb(self, get_next_return): ] self.current_page.extend( [ - FileProperties._from_generated(i) for i in self._response.segment.file_items - ] # pylint: disable=protected-access + 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 From 1e726402c078391c6036311c8858fcea06ba25ee Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 30 Mar 2026 12:21:47 -0700 Subject: [PATCH 15/45] remove redudant lines --- .../azure/storage/fileshare/_file_client.py | 2 -- .../azure/storage/fileshare/aio/_file_client_async.py | 2 -- 2 files changed, 4 deletions(-) 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 cacdc63cca78..79d5f91b0462 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 @@ -1525,7 +1525,6 @@ def get_ranges( 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 - options["sharesnapshot"] = self.snapshot try: ranges = self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1585,7 +1584,6 @@ def get_ranges_diff( ) options["allow_trailing_dot"] = self.allow_trailing_dot options["file_request_intent"] = self.file_request_intent - options["sharesnapshot"] = self.snapshot try: ranges = self._client.file.get_range_list(**options) except HttpResponseError as error: 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 bd311338cdc1..f8f5ffb86d3b 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 @@ -1541,7 +1541,6 @@ async def get_ranges( 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 - options["sharesnapshot"] = self.snapshot try: ranges = await self._client.file.get_range_list(**options) except HttpResponseError as error: @@ -1601,7 +1600,6 @@ async def get_ranges_diff( ) options["allow_trailing_dot"] = self.allow_trailing_dot options["file_request_intent"] = self.file_request_intent - options["sharesnapshot"] = self.snapshot try: ranges = await self._client.file.get_range_list(**options) except HttpResponseError as error: From d42cf3493796f0e29f7b50cca23c4dcec2c93a8b Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 30 Mar 2026 13:17:46 -0700 Subject: [PATCH 16/45] tests all passing --- .../fileshare/_generated/models/_patch.py | 92 +++- .../azure/storage/fileshare/_models.py | 480 ++++++++---------- .../fileshare/_shared/response_handlers.py | 44 +- 3 files changed, 312 insertions(+), 304 deletions(-) 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 87676c65a8f0..f2bd6d2eba47 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,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -7,9 +8,96 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +from typing import List +from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level + +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() + } + 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 + + +__all__: List[str] = [] def patch_sdk(): @@ -18,4 +106,4 @@ def patch_sdk(): `patch_sdk` is a last resort escape hatch that allows you to do customizations you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize - """ + """ \ No newline at end of file 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 31f6ce0f520a..cf3bd013d76a 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,4 +1,3 @@ -# 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,11 +6,11 @@ # 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 - -import datetime as _datetime_module - from typing_extensions import Self from azure.core import CaseInsensitiveEnumMeta @@ -39,31 +38,10 @@ from ._generated.models import ShareRootSquash -def _parse_datetime(value): - """Parse a datetime value that may already be a datetime object (new generated code) or a string (old). - - :param value: The value to parse. - :type value: str or ~datetime.datetime or None - :returns: A datetime object or None. - :rtype: ~datetime.datetime or None - """ - if value is None: - return None - if isinstance(value, _datetime_module.datetime): - return value - try: - return Deserializer.deserialize_rfc(value) - except (TypeError, ValueError, AttributeError): - try: - return Deserializer.deserialize_iso(value) - except (TypeError, ValueError, AttributeError): - return value - - 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): @@ -79,14 +57,13 @@ class RetentionPolicy(GeneratedRetentionPolicy): All data older than this value will be deleted. """ - enabled: bool + enabled: bool = False """Indicates whether a retention policy is enabled for the storage service.""" - days: Optional[int] + days: Optional[int] = None """Indicates the number of days that metrics or logging or soft-deleted data should be retained. All data older than this value will be deleted.""" def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: - self._data = {} self.enabled = enabled self.days = days if self.enabled and (self.days is None): @@ -118,21 +95,20 @@ class Metrics(GeneratedMetrics): Determines how long the associated data should persist. """ - version: str + version: str = '1.0' """The version of Storage Analytics to configure.""" - enabled: bool + enabled: bool = False """Indicates whether metrics are enabled for the File service.""" include_apis: bool """Indicates whether metrics should generate summary statistics for called API operations.""" - retention_policy: RetentionPolicy + retention_policy: RetentionPolicy = RetentionPolicy() """Determines how long the associated data should persist.""" def __init__(self, **kwargs: Any) -> None: - self._data = {} - 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): @@ -142,9 +118,7 @@ def _from_generated(cls, generated): version=generated.version, enabled=generated.enabled, include_apis=generated.include_apis, - retention_policy=RetentionPolicy._from_generated( # pylint: disable=protected-access - generated.retention_policy - ), + retention_policy=RetentionPolicy._from_generated(generated.retention_policy) # pylint: disable=protected-access ) @@ -194,12 +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._data = {} - 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]]: @@ -239,8 +212,7 @@ class SmbMultichannel(GeneratedSmbMultichannel): enabled: bool """If SMB Multichannel is enabled.""" - def __init__(self, *, enabled: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self._data = {} + def __init__(self, *, enabled: bool, **kwargs: Any) -> None: self.enabled = enabled @@ -253,8 +225,7 @@ class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): required: bool """If encryption in transit is enabled.""" - def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self._data = {} + def __init__(self, *, required: bool, **kwargs: Any) -> None: self.required = required @@ -270,14 +241,13 @@ class ShareSmbSettings(GeneratedShareSmbSettings): encryption_in_transit: Optional[SmbEncryptionInTransit] """Sets the encryption in transit settings.""" - def __init__( # pylint: disable=unused-argument + def __init__( self, *, multichannel: Optional[SmbMultichannel] = None, encryption_in_transit: Optional[SmbEncryptionInTransit] = None, **kwargs: Any ) -> None: - self._data = {} self.multichannel = multichannel self.encryption_in_transit = encryption_in_transit if self.multichannel is None and self.encryption_in_transit is None: @@ -293,8 +263,7 @@ class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): required: bool """If encryption in transit is enabled.""" - def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self._data = {} + def __init__(self, *, required: bool, **kwargs: Any) -> None: self.required = required @@ -307,10 +276,7 @@ class ShareNfsSettings(GeneratedShareNfsSettings): encryption_in_transit: NfsEncryptionInTransit """Sets the encryption in transit settings.""" - def __init__( - self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any # pylint: disable=unused-argument - ) -> None: - self._data = {} + def __init__(self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any) -> None: self.encryption_in_transit = encryption_in_transit @@ -328,10 +294,13 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): nfs: Optional[ShareNfsSettings] """Sets the NFS settings.""" - def __init__( # pylint: disable=unused-argument - self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any + def __init__( + self, + *, + smb: Optional[ShareSmbSettings] = None, + nfs: Optional[ShareNfsSettings] = None, + **kwargs: Any ) -> None: - self._data = {} self.smb = smb self.nfs = nfs if self.smb is None and self.nfs is None: @@ -377,20 +346,22 @@ 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 @@ -408,11 +379,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) @@ -472,12 +443,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._data = {} self.start = start self.expiry = expiry self.permission = permission @@ -494,9 +463,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): @@ -547,8 +516,7 @@ 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, @@ -556,12 +524,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): @@ -636,40 +604,39 @@ class ShareProperties(DictMixin): def __init__(self, **kwargs: Any) -> None: self.name = None # type: ignore [assignment] - self.last_modified = _parse_datetime(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 = 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" - ) + 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')) @classmethod def _from_generated(cls, generated): @@ -691,11 +658,8 @@ 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 @@ -704,11 +668,9 @@ 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 @@ -737,14 +699,15 @@ 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 @@ -761,8 +724,7 @@ 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) @@ -772,9 +734,7 @@ 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 @@ -815,20 +775,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): @@ -865,10 +825,14 @@ 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 @@ -882,16 +846,13 @@ 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 @@ -923,8 +884,7 @@ 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, @@ -933,7 +893,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 @@ -945,22 +905,20 @@ 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: @@ -984,9 +942,8 @@ 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 @@ -1028,40 +985,31 @@ 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 = _parse_datetime(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 = ( - _parse_datetime(kwargs.get("x-ms-file-change-time")) - if (kwargs.get("x-ms-file-change-time") is not None) - else None - ) - self.creation_time = ( - _parse_datetime(kwargs.get("x-ms-file-creation-time")) - if (kwargs.get("x-ms-file-creation-time") is not None) - else None - ) - self.last_write_time = ( - _parse_datetime(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): @@ -1109,14 +1057,15 @@ 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 @@ -1133,8 +1082,7 @@ 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) @@ -1143,16 +1091,8 @@ 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) # 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 - ] - ) + 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 return self._response.next_marker or None, self.current_page @@ -1203,14 +1143,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): @@ -1286,51 +1226,45 @@ 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 = _parse_datetime(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] + last_modified = kwargs.get('Last-Modified') + if isinstance(last_modified, str): + last_modified = Deserializer.deserialize_rfc(last_modified) + self.last_modified = 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 = ( - _parse_datetime(kwargs.get("x-ms-file-change-time")) - if (kwargs.get("x-ms-file-change-time") is not None) - else None - ) - self.creation_time = ( - _parse_datetime(kwargs.get("x-ms-file-creation-time")) - if (kwargs.get("x-ms-file-creation-time") is not None) - else None - ) - self.last_write_time = ( - _parse_datetime(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): @@ -1351,7 +1285,6 @@ def _from_generated(cls, generated): class ShareProtocols(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Enabled protocols on the share""" - SMB = "SMB" NFS = "NFS" @@ -1381,17 +1314,20 @@ 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 @@ -1409,10 +1345,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) @@ -1421,8 +1357,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/_shared/response_handlers.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/response_handlers.py index 16d041bb8c33..a1637f3976ca 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,4 +1,3 @@ -# 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 @@ -177,11 +176,8 @@ 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: @@ -201,34 +197,22 @@ def process_storage_error(storage_error) -> NoReturn: # type: ignore [misc] # p raise error from exc -def _extract_text(value): - """Extract text from a value that may be an XML Element. - - :param Any value: The value to extract text from. - :returns: The text content if value is an XML Element, otherwise the value itself. - :rtype: str or None - """ - if isinstance(value, Element): - return value.text - return value - - def parse_to_internal_user_delegation_key(service_user_delegation_key): internal_user_delegation_key = UserDelegationKey() - internal_user_delegation_key.signed_oid = _extract_text(service_user_delegation_key.signed_oid) - internal_user_delegation_key.signed_tid = _extract_text(service_user_delegation_key.signed_tid) - internal_user_delegation_key.signed_delegated_user_tid = _extract_text( - service_user_delegation_key.signed_delegated_user_tid - ) - signed_start = _extract_text(service_user_delegation_key.signed_start) + 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 = ( - signed_start if isinstance(signed_start, str) else _to_utc_datetime(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) ) - signed_expiry = _extract_text(service_user_delegation_key.signed_expiry) internal_user_delegation_key.signed_expiry = ( - signed_expiry if isinstance(signed_expiry, str) else _to_utc_datetime(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 = _extract_text(service_user_delegation_key.signed_service) - internal_user_delegation_key.signed_version = _extract_text(service_user_delegation_key.signed_version) - internal_user_delegation_key.value = _extract_text(service_user_delegation_key.value) + 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 return internal_user_delegation_key From 2adbc219468d27228d7573316ef4d163cdcdc231 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 30 Mar 2026 13:43:03 -0700 Subject: [PATCH 17/45] pylint --- .../azure/storage/fileshare/_models.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) 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 cf3bd013d76a..348fe0cfc07b 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 @@ -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 @@ -247,7 +247,7 @@ def __init__( multichannel: Optional[SmbMultichannel] = None, encryption_in_transit: Optional[SmbEncryptionInTransit] = None, **kwargs: Any - ) -> None: + ) -> None: # pylint: disable=unused-argument self.multichannel = multichannel self.encryption_in_transit = encryption_in_transit if self.multichannel is None and self.encryption_in_transit is 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,7 @@ 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__(self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any) -> None: # pylint: disable=unused-argument self.encryption_in_transit = encryption_in_transit @@ -300,7 +300,7 @@ def __init__( smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any - ) -> None: + ) -> None: # pylint: disable=unused-argument self.smb = smb self.nfs = nfs if self.smb is None and self.nfs is None: From d5df691ee919f4705483e4eabbc424da91bf1104 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 1 Apr 2026 15:48:29 -0700 Subject: [PATCH 18/45] regen --- .../storage/fileshare/_generated/_client.py | 2 +- .../fileshare/_generated/_configuration.py | 4 +- .../fileshare/_generated/aio/_client.py | 2 +- .../_generated/aio/_configuration.py | 4 +- .../_generated/aio/operations/_operations.py | 14 ++ .../fileshare/_generated/models/_patch.py | 2 +- .../_generated/operations/_operations.py | 124 +++++++++++------- 7 files changed, 94 insertions(+), 58 deletions(-) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py index 1d46a86c7891..7cd63e8440a5 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py @@ -39,7 +39,7 @@ class FileClient: # pylint: disable=client-accepts-api-version-keyword :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-04-06". Default value is "2026-04-06". Note that overriding this default value may + are "2026-06-06". Default value is "2026-06-06". Note that overriding this default value may result in unsupported behavior. :paramtype version: str """ 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 5fbde0018e32..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 @@ -28,13 +28,13 @@ class FileClientConfiguration: # pylint: disable=too-many-instance-attributes :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-04-06". Default value is "2026-04-06". Note that overriding this default value may + 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, url: str, credential: "TokenCredential", **kwargs: Any) -> None: - version: str = kwargs.pop("version", "2026-04-06") + version: str = kwargs.pop("version", "2026-06-06") if url is None: raise ValueError("Parameter 'url' must not be None.") diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py index 52e67efdb6ca..5d099a8eefa8 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py @@ -39,7 +39,7 @@ class FileClient: # pylint: disable=client-accepts-api-version-keyword :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-04-06". Default value is "2026-04-06". Note that overriding this default value may + are "2026-06-06". Default value is "2026-06-06". Note that overriding this default value may result in unsupported behavior. :paramtype version: str """ 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 3dfaf3a4772d..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 @@ -28,13 +28,13 @@ class FileClientConfiguration: # pylint: disable=too-many-instance-attributes :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-04-06". Default value is "2026-04-06". Note that overriding this default value may + 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, url: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - version: str = kwargs.pop("version", "2026-04-06") + version: str = kwargs.pop("version", "2026-06-06") if url is None: raise ValueError("Parameter 'url' must not be None.") 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 index 3ed33ee58d63..baec0105608a 100644 --- 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 @@ -3403,6 +3403,8 @@ async def create( # pylint: disable=too-many-locals content_md5: Optional[bytes] = None, file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, optional_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. @@ -3492,6 +3494,13 @@ async def create( # pylint: disable=too-many-locals :keyword optional_content_length: Optional. Specifies the content length of the file. Default value is None. :paramtype optional_content_length: int + :keyword structured_body_type: Required if the request body is a structured message. 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: @@ -3543,6 +3552,8 @@ async def create( # pylint: disable=too-many-locals content_md5=content_md5, file_property_semantics=file_property_semantics, optional_content_length=optional_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, @@ -3599,6 +3610,9 @@ async def create( # pylint: disable=too-many-locals 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( 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 f2bd6d2eba47..3cb55fced6ec 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 @@ -106,4 +106,4 @@ def patch_sdk(): `patch_sdk` is a last resort escape hatch that allows you to do customizations you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize - """ \ No newline at end of file + """ 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 index 9b212610bf8c..a4180594282f 100644 --- 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 @@ -50,7 +50,7 @@ def build_service_set_properties_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "/?restype=service&comp=properties" @@ -76,7 +76,7 @@ def build_service_get_properties_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -108,7 +108,7 @@ def build_service_list_shares_segment_request( # pylint: disable=name-too-long _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -142,7 +142,7 @@ def build_service_get_user_delegation_key_request( # pylint: disable=name-too-l _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -181,7 +181,7 @@ def build_share_create_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share" @@ -246,7 +246,7 @@ def build_share_get_properties_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share" @@ -278,7 +278,7 @@ def build_share_delete_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share" @@ -313,7 +313,7 @@ def build_share_acquire_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=lease" @@ -348,7 +348,7 @@ def build_share_release_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=lease" @@ -381,7 +381,7 @@ def build_share_change_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=lease" @@ -415,7 +415,7 @@ def build_share_renew_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=lease" @@ -448,7 +448,7 @@ def build_share_break_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=lease" @@ -481,7 +481,7 @@ def build_share_create_snapshot_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=snapshot" @@ -509,7 +509,7 @@ def build_share_create_permission_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=filepermission" @@ -538,7 +538,7 @@ def build_share_get_permission_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -582,7 +582,7 @@ def build_share_set_properties_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=properties" @@ -645,7 +645,7 @@ def build_share_set_metadata_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=metadata" @@ -675,7 +675,7 @@ def build_share_get_access_policy_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -707,7 +707,7 @@ def build_share_set_access_policy_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=acl" @@ -737,7 +737,7 @@ def build_share_get_statistics_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -769,7 +769,7 @@ def build_share_restore_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=share&comp=undelete" @@ -813,7 +813,7 @@ def build_directory_create_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=directory" @@ -870,7 +870,7 @@ def build_directory_get_properties_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=directory" @@ -900,7 +900,7 @@ def build_directory_delete_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=directory" @@ -938,7 +938,7 @@ def build_directory_set_properties_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=directory&comp=properties" @@ -989,7 +989,7 @@ def build_directory_set_metadata_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=directory&comp=metadata" @@ -1025,7 +1025,7 @@ def build_directory_list_files_and_directories_segment_request( # pylint: disab _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -1072,7 +1072,7 @@ def build_directory_list_handles_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -1115,7 +1115,7 @@ def build_directory_force_close_handles_request( # pylint: disable=name-too-lon _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=forceclosehandles" @@ -1164,7 +1164,7 @@ def build_directory_rename_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=directory&comp=rename" @@ -1243,6 +1243,8 @@ def build_file_create_request( # pylint: disable=too-many-locals,too-many-state content_md5: Optional[bytes] = None, file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, optional_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 {}) @@ -1250,7 +1252,7 @@ def build_file_create_request( # pylint: disable=too-many-locals,too-many-state 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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "" @@ -1318,6 +1320,12 @@ def build_file_create_request( # pylint: disable=too-many-locals,too-many-state ) if optional_content_length is not None: _headers["Content-Length"] = _SERIALIZER.header("optional_content_length", optional_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) @@ -1336,7 +1344,7 @@ def build_file_download_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -1379,7 +1387,7 @@ def build_file_get_properties_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "" @@ -1412,7 +1420,7 @@ def build_file_delete_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "" @@ -1460,7 +1468,7 @@ def build_file_set_http_headers_request( # pylint: disable=too-many-locals _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=properties" @@ -1530,7 +1538,7 @@ def build_file_set_metadata_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=metadata" @@ -1565,7 +1573,7 @@ def build_file_acquire_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=lease" @@ -1600,7 +1608,7 @@ def build_file_release_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=lease" @@ -1633,7 +1641,7 @@ def build_file_change_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=lease" @@ -1667,7 +1675,7 @@ def build_file_break_lease_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=lease" @@ -1707,7 +1715,7 @@ def build_file_upload_range_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=range" @@ -1766,7 +1774,7 @@ def build_file_upload_range_from_url_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=range" @@ -1829,7 +1837,7 @@ def build_file_get_range_list_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -1889,7 +1897,7 @@ def build_file_start_copy_request( # pylint: disable=too-many-locals _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "" @@ -1967,7 +1975,7 @@ def build_file_abort_copy_request( 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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=copy" @@ -2002,7 +2010,7 @@ def build_file_list_handles_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) accept = _headers.pop("Accept", "application/xml") # Construct URL @@ -2042,7 +2050,7 @@ def build_file_force_close_handles_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=forceclosehandles" @@ -2090,7 +2098,7 @@ def build_file_rename_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?comp=rename" @@ -2159,7 +2167,7 @@ def build_file_create_symbolic_link_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=symboliclink" @@ -2198,7 +2206,7 @@ def build_file_get_symbolic_link_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=symboliclink" @@ -2228,7 +2236,7 @@ def build_file_create_hard_link_request( _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-04-06")) + version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL _url = "?restype=hardlink" @@ -5561,6 +5569,8 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals content_md5: Optional[bytes] = None, file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, optional_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. @@ -5650,6 +5660,13 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals :keyword optional_content_length: Optional. Specifies the content length of the file. Default value is None. :paramtype optional_content_length: int + :keyword structured_body_type: Required if the request body is a structured message. 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: @@ -5701,6 +5718,8 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals content_md5=content_md5, file_property_semantics=file_property_semantics, optional_content_length=optional_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, @@ -5757,6 +5776,9 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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( From a580c5cb2cdd2cc0d1f10aa9cd1ac6b2071c07dd Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 3 Apr 2026 09:42:18 -0700 Subject: [PATCH 19/45] pylint --- .../azure/storage/fileshare/_models.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 348fe0cfc07b..d48b3af4a23e 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 @@ -242,12 +242,12 @@ class ShareSmbSettings(GeneratedShareSmbSettings): """Sets the encryption in transit settings.""" def __init__( - self, + self, # pylint: disable=unused-argument *, multichannel: Optional[SmbMultichannel] = None, encryption_in_transit: Optional[SmbEncryptionInTransit] = None, **kwargs: Any - ) -> None: # pylint: disable=unused-argument + ) -> None: self.multichannel = multichannel self.encryption_in_transit = encryption_in_transit if self.multichannel is None and self.encryption_in_transit is None: @@ -295,12 +295,12 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): """Sets the NFS settings.""" def __init__( - self, + self, # pylint: disable=unused-argument *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any - ) -> None: # pylint: disable=unused-argument + ) -> None: self.smb = smb self.nfs = nfs if self.smb is None and self.nfs is None: From 2253b7bb09ff03644402c18bb7827e9009e39ced Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 12:32:38 -0700 Subject: [PATCH 20/45] regen --- .../_generated/aio/operations/_operations.py | 50 ++++++++++--------- .../_generated/operations/_operations.py | 50 ++++++++++--------- 2 files changed, 54 insertions(+), 46 deletions(-) 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 index baec0105608a..1b86c0b51344 100644 --- 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 @@ -1707,8 +1707,8 @@ async def set_properties( # pylint: disable=too-many-locals :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. :paramtype file_request_intent: str or ~azure.storage.fileshare._generated.models.ShareTokenIntent - :keyword share_provisioned_iops: Optional. Specifies the provisioned number of input/output - operations per second (IOPS) of the share. Default value is None. + :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. @@ -3494,8 +3494,9 @@ async def create( # pylint: disable=too-many-locals :keyword optional_content_length: Optional. Specifies the content length of the file. Default value is None. :paramtype optional_content_length: int - :keyword structured_body_type: Required if the request body is a structured message. Specifies - the message schema version and properties. Default value is None. + :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 @@ -3655,7 +3656,8 @@ async def download( :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. :paramtype file_request_intent: str or ~azure.storage.fileshare._generated.models.ShareTokenIntent - :keyword structured_body_type: Optional. Used for structured get operations. Default value is + :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] @@ -3799,8 +3801,8 @@ async def get_properties( """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, when present, - specifies the share snapshot to query. Default value is None. + :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 @@ -4677,7 +4679,7 @@ async def upload_range( # pylint: disable=too-many-locals :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 - data during transport. Default value is None. + 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. @@ -4692,11 +4694,13 @@ async def upload_range( # pylint: disable=too-many-locals :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. :paramtype file_request_intent: str or ~azure.storage.fileshare._generated.models.ShareTokenIntent - :keyword structured_body_type: Optional. Used for structured put operations. Default value is + :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: Optional. Used for structured put operations to specify - content length. Default value is None. + :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 @@ -4941,8 +4945,8 @@ async def get_range_list( ) -> _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, when present, - specifies the share snapshot to query. Default value is None. + :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. @@ -5326,8 +5330,8 @@ async def list_handles( :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, when present, - specifies the share snapshot to query. Default value is None. + :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. @@ -5430,8 +5434,8 @@ async def force_close_handles( :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, when present, - specifies the share snapshot to query. Default value is None. + :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. @@ -5546,8 +5550,8 @@ async def rename( # pylint: disable=too-many-locals :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 file has an active lease. Default - value is None. + :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. @@ -5690,8 +5694,8 @@ async def create_symbolic_link( ) -> None: """Creates a symbolic link to a target file. NFS only. - :keyword link_text: NFS only. Required. The path to the original file, the symbolic link is - pointing to. Required. + :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 @@ -5804,8 +5808,8 @@ async def get_symbolic_link( :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, when present, - specifies the share snapshot to query. Default value is None. + :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 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 index a4180594282f..9ebabdd0039d 100644 --- 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 @@ -3873,8 +3873,8 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. :paramtype file_request_intent: str or ~azure.storage.fileshare._generated.models.ShareTokenIntent - :keyword share_provisioned_iops: Optional. Specifies the provisioned number of input/output - operations per second (IOPS) of the share. Default value is None. + :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. @@ -5660,8 +5660,9 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals :keyword optional_content_length: Optional. Specifies the content length of the file. Default value is None. :paramtype optional_content_length: int - :keyword structured_body_type: Required if the request body is a structured message. Specifies - the message schema version and properties. Default value is None. + :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 @@ -5821,7 +5822,8 @@ def download( :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. :paramtype file_request_intent: str or ~azure.storage.fileshare._generated.models.ShareTokenIntent - :keyword structured_body_type: Optional. Used for structured get operations. Default value is + :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] @@ -5965,8 +5967,8 @@ def get_properties( """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, when present, - specifies the share snapshot to query. Default value is None. + :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 @@ -6843,7 +6845,7 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc :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 - data during transport. Default value is None. + 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. @@ -6858,11 +6860,13 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. :paramtype file_request_intent: str or ~azure.storage.fileshare._generated.models.ShareTokenIntent - :keyword structured_body_type: Optional. Used for structured put operations. Default value is + :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: Optional. Used for structured put operations to specify - content length. Default value is None. + :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 @@ -7107,8 +7111,8 @@ def get_range_list( ) -> _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, when present, - specifies the share snapshot to query. Default value is None. + :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. @@ -7492,8 +7496,8 @@ def list_handles( :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, when present, - specifies the share snapshot to query. Default value is None. + :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. @@ -7596,8 +7600,8 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements :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, when present, - specifies the share snapshot to query. Default value is None. + :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. @@ -7712,8 +7716,8 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals :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 file has an active lease. Default - value is None. + :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. @@ -7856,8 +7860,8 @@ def create_symbolic_link( # pylint: disable=inconsistent-return-statements ) -> None: """Creates a symbolic link to a target file. NFS only. - :keyword link_text: NFS only. Required. The path to the original file, the symbolic link is - pointing to. Required. + :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 @@ -7970,8 +7974,8 @@ def get_symbolic_link( # pylint: disable=inconsistent-return-statements :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, when present, - specifies the share snapshot to query. Default value is None. + :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 From 42213a5447a21b0daa33bc95b20d59e464eb6f79 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 12:40:02 -0700 Subject: [PATCH 21/45] Apply suggestion from @l0lawrence --- .../azure/storage/fileshare/_generated/aio/_patch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 3cdf362eaca3..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 @@ -48,7 +48,7 @@ def __init__(self, url: str, credential: Optional["AsyncTokenCredential"] = None if url is None: raise ValueError("Parameter 'url' must not be None.") - version: str = kwargs.pop("version", "2026-04-06") + version: str = kwargs.pop("version", "2026-06-06") self.url = url self.credential = credential self.version = version From 29e2337caab00f683fa5b3a9bf6cc01b7f51dbdc Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 12:40:24 -0700 Subject: [PATCH 22/45] Apply suggestion from @l0lawrence --- .../azure/storage/fileshare/_generated/_patch.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 97c2db61e797..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 @@ -48,7 +48,7 @@ def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **k if url is None: raise ValueError("Parameter 'url' must not be None.") - version: str = kwargs.pop("version", "2026-04-06") + version: str = kwargs.pop("version", "2026-06-06") self.url = url self.credential = credential self.version = version From dc9ba6deca6a3b3563974ef8b75d07ac601ad69b Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 13:19:23 -0700 Subject: [PATCH 23/45] prproject --- sdk/storage/azure-storage-file-share/pyproject.toml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index a9a3c3d0ce7f..461f2163c9e6 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -34,11 +34,17 @@ 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" From 0273df0f9ce24272555a1bf302638adc8eaa6cf9 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Mon, 6 Apr 2026 13:28:48 -0700 Subject: [PATCH 24/45] Apply suggestion from @l0lawrence --- sdk/storage/azure-storage-file-share/pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index 461f2163c9e6..8bcd9b911dfa 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta" [project] name = "azure-storage-file-share" authors = [ - { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, + { name = "Microsoft Corporation", email = "ascl@microsoft.com" }, ] description = "Microsoft Corporation Azure Storage File Share Client Library for Python" license = "MIT" From e875494679f8a5a6c337d8c7c797fa6bfa3cdf50 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 14 Apr 2026 10:16:42 -0700 Subject: [PATCH 25/45] regen w new config --- .../azure-storage-file-share/MANIFEST.in | 3 +- .../azure-storage-file-share/_metadata.json | 4 +- .../apiview-properties.json | 310 +- .../storage/fileshare/_generated/_client.py | 16 +- .../fileshare/_generated/_utils/model_base.py | 219 +- .../fileshare/_generated/aio/_client.py | 16 +- .../_generated/aio/operations/__init__.py | 8 +- .../_generated/aio/operations/_operations.py | 5152 ++++++------ .../fileshare/_generated/models/_models.py | 14 +- .../_generated/operations/__init__.py | 8 +- .../_generated/operations/_operations.py | 7092 ++++++++--------- .../azure/storage/fileshare/_models.py | 415 +- .../azure/storage/fileshare/_parser.py | 3 +- .../azure/storage/fileshare/_serialize.py | 60 +- .../storage/fileshare/_shared/base_client.py | 2 +- .../fileshare/_shared/response_handlers.py | 8 +- .../tests/conftest.py | 2 +- .../tests/test_directory.py | 7 +- .../tests/test_directory_async.py | 7 +- .../tests/test_file.py | 9 +- .../tests/test_file_async.py | 8 +- .../tests/test_file_client.py | 17 +- .../tests/test_file_client_async.py | 13 +- 23 files changed, 6694 insertions(+), 6699 deletions(-) diff --git a/sdk/storage/azure-storage-file-share/MANIFEST.in b/sdk/storage/azure-storage-file-share/MANIFEST.in index 6267830e6cc6..1da294d9d659 100644 --- a/sdk/storage/azure-storage-file-share/MANIFEST.in +++ b/sdk/storage/azure-storage-file-share/MANIFEST.in @@ -1,8 +1,7 @@ include *.md include LICENSE -include azure/storage/fileshare/_generated/py.typed +include azure/storage/fileshare/py.typed recursive-include tests *.py recursive-include samples *.py *.md include azure/__init__.py include azure/storage/__init__.py -include azure/storage/fileshare/__init__.py diff --git a/sdk/storage/azure-storage-file-share/_metadata.json b/sdk/storage/azure-storage-file-share/_metadata.json index b7d0ad5ff9ee..48cc0626e1f3 100644 --- a/sdk/storage/azure-storage-file-share/_metadata.json +++ b/sdk/storage/azure-storage-file-share/_metadata.json @@ -1,6 +1,6 @@ { - "apiVersion": "2026-04-06", + "apiVersion": "2026-06-06", "apiVersions": { - "Storage.File": "2026-04-06" + "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 index 629919ac0239..1408a4caf6a8 100644 --- a/sdk/storage/azure-storage-file-share/apiview-properties.json +++ b/sdk/storage/azure-storage-file-share/apiview-properties.json @@ -1,160 +1,160 @@ { "CrossLanguagePackageId": "Storage.File", "CrossLanguageDefinitionId": { - "azure.storage.fileshare._generated.models.AccessPolicy": "Storage.File.AccessPolicy", - "azure.storage.fileshare._generated.models.ClearRange": "Storage.File.ClearRange", - "azure.storage.fileshare._generated.models.CorsRule": "Storage.File.CorsRule", - "azure.storage.fileshare._generated.models.DirectoryItem": "Storage.File.DirectoryItem", - "azure.storage.fileshare._generated.models.Error": "Storage.File.Error", - "azure.storage.fileshare._generated.models.FileItem": "Storage.File.FileItem", - "azure.storage.fileshare._generated.models.FileProperty": "Storage.File.FileProperty", - "azure.storage.fileshare._generated.models.FileRange": "Storage.File.FileRange", - "azure.storage.fileshare._generated.models.FilesAndDirectoriesListSegment": "Storage.File.FilesAndDirectoriesListSegment", - "azure.storage.fileshare._generated.models.HandleItem": "Storage.File.HandleItem", - "azure.storage.fileshare._generated.models.KeyInfo": "Storage.File.KeyInfo", - "azure.storage.fileshare._generated.models.ListFilesAndDirectoriesSegmentResponse": "Storage.File.ListFilesAndDirectoriesSegmentResponse", - "azure.storage.fileshare._generated.models.ListHandlesResponse": "Storage.File.ListHandlesResponse", - "azure.storage.fileshare._generated.models.ListSharesResponse": "Storage.File.ListSharesResponse", - "azure.storage.fileshare._generated.models.Metrics": "Storage.File.Metrics", - "azure.storage.fileshare._generated.models.RetentionPolicy": "Storage.File.RetentionPolicy", - "azure.storage.fileshare._generated.models.ShareFileRangeList": "Storage.File.ShareFileRangeList", - "azure.storage.fileshare._generated.models.ShareItemInternal": "Storage.File.ShareItemInternal", - "azure.storage.fileshare._generated.models.ShareNfsSettings": "Storage.File.ShareNfsSettings", - "azure.storage.fileshare._generated.models.ShareNfsSettingsEncryptionInTransit": "Storage.File.ShareNfsSettingsEncryptionInTransit", - "azure.storage.fileshare._generated.models.SharePermission": "Storage.File.SharePermission", - "azure.storage.fileshare._generated.models.SharePropertiesInternal": "Storage.File.SharePropertiesInternal", - "azure.storage.fileshare._generated.models.ShareProtocolSettings": "Storage.File.ShareProtocolSettings", - "azure.storage.fileshare._generated.models.ShareSmbSettings": "Storage.File.ShareSmbSettings", - "azure.storage.fileshare._generated.models.ShareSmbSettingsEncryptionInTransit": "Storage.File.ShareSmbSettingsEncryptionInTransit", - "azure.storage.fileshare._generated.models.ShareStats": "Storage.File.ShareStats", - "azure.storage.fileshare._generated.models.SignedIdentifier": "Storage.File.SignedIdentifier", - "azure.storage.fileshare._generated.models.SignedIdentifiers": "Storage.File.SignedIdentifiers", - "azure.storage.fileshare._generated.models.SmbMultichannel": "Storage.File.SmbMultichannel", - "azure.storage.fileshare._generated.models.StorageServiceProperties": "Storage.File.StorageServiceProperties", - "azure.storage.fileshare._generated.models.StringEncoded": "Storage.File.StringEncoded", - "azure.storage.fileshare._generated.models.UserDelegationKey": "Storage.File.UserDelegationKey", - "azure.storage.fileshare._generated.models.StorageErrorCode": "Storage.File.StorageErrorCode", - "azure.storage.fileshare._generated.models.ShareTokenIntent": "Storage.File.ShareTokenIntent", - "azure.storage.fileshare._generated.models.LeaseStatusType": "Storage.File.LeaseStatusType", - "azure.storage.fileshare._generated.models.LeaseStateType": "Storage.File.LeaseStateType", - "azure.storage.fileshare._generated.models.LeaseDurationType": "Storage.File.LeaseDurationType", - "azure.storage.fileshare._generated.models.ShareRootSquash": "Storage.File.ShareRootSquash", - "azure.storage.fileshare._generated.models.ListSharesIncludeType": "Storage.File.ListSharesIncludeType", - "azure.storage.fileshare._generated.models.ShareAccessTier": "Storage.File.ShareAccessTier", - "azure.storage.fileshare._generated.models.DeleteSnapshotsOptionType": "Storage.File.DeleteSnapshotsOptionType", - "azure.storage.fileshare._generated.models.FilePermissionFormat": "Storage.File.FilePermissionFormat", - "azure.storage.fileshare._generated.models.NfsFileType": "Storage.File.NfsFileType", - "azure.storage.fileshare._generated.models.FilePropertySemantics": "Storage.File.FilePropertySemantics", - "azure.storage.fileshare._generated.models.ListFilesIncludeType": "Storage.File.ListFilesIncludeType", - "azure.storage.fileshare._generated.models.AccessRight": "Storage.File.AccessRight", - "azure.storage.fileshare._generated.models.CopyStatus": "Storage.File.CopyStatus", - "azure.storage.fileshare._generated.models.FileRangeWriteType": "Storage.File.FileRangeWriteType", - "azure.storage.fileshare._generated.models.FileLastWrittenMode": "Storage.File.FileLastWrittenMode", - "azure.storage.fileshare._generated.models.FileRangeWriteFromUrlType": "Storage.File.FileRangeWriteFromUrlType", - "azure.storage.fileshare._generated.models.PermissionCopyModeType": "Storage.File.PermissionCopyModeType", - "azure.storage.fileshare._generated.models.ModeCopyMode": "Storage.File.ModeCopyMode", - "azure.storage.fileshare._generated.models.OwnerCopyMode": "Storage.File.OwnerCopyMode", - "azure.storage.fileshare._generated.operations.ServiceOperations.set_properties": "Storage.File.Service.setProperties", - "azure.storage.fileshare._generated.aio.operations.ServiceOperations.set_properties": "Storage.File.Service.setProperties", - "azure.storage.fileshare._generated.operations.ServiceOperations.get_properties": "Storage.File.Service.getProperties", - "azure.storage.fileshare._generated.aio.operations.ServiceOperations.get_properties": "Storage.File.Service.getProperties", - "azure.storage.fileshare._generated.operations.ServiceOperations.list_shares_segment": "Storage.File.Service.listSharesSegment", - "azure.storage.fileshare._generated.aio.operations.ServiceOperations.list_shares_segment": "Storage.File.Service.listSharesSegment", - "azure.storage.fileshare._generated.operations.ServiceOperations.get_user_delegation_key": "Storage.File.Service.getUserDelegationKey", - "azure.storage.fileshare._generated.aio.operations.ServiceOperations.get_user_delegation_key": "Storage.File.Service.getUserDelegationKey", - "azure.storage.fileshare._generated.operations.ShareOperations.create": "Storage.File.Share.create", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.create": "Storage.File.Share.create", - "azure.storage.fileshare._generated.operations.ShareOperations.get_properties": "Storage.File.Share.getProperties", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.get_properties": "Storage.File.Share.getProperties", - "azure.storage.fileshare._generated.operations.ShareOperations.delete": "Storage.File.Share.delete", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.delete": "Storage.File.Share.delete", - "azure.storage.fileshare._generated.operations.ShareOperations.acquire_lease": "Storage.File.Share.acquireLease", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.acquire_lease": "Storage.File.Share.acquireLease", - "azure.storage.fileshare._generated.operations.ShareOperations.release_lease": "Storage.File.Share.releaseLease", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.release_lease": "Storage.File.Share.releaseLease", - "azure.storage.fileshare._generated.operations.ShareOperations.change_lease": "Storage.File.Share.changeLease", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.change_lease": "Storage.File.Share.changeLease", - "azure.storage.fileshare._generated.operations.ShareOperations.renew_lease": "Storage.File.Share.renewLease", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.renew_lease": "Storage.File.Share.renewLease", - "azure.storage.fileshare._generated.operations.ShareOperations.break_lease": "Storage.File.Share.breakLease", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.break_lease": "Storage.File.Share.breakLease", - "azure.storage.fileshare._generated.operations.ShareOperations.create_snapshot": "Storage.File.Share.createSnapshot", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.create_snapshot": "Storage.File.Share.createSnapshot", - "azure.storage.fileshare._generated.operations.ShareOperations.create_permission": "Storage.File.Share.createPermission", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.create_permission": "Storage.File.Share.createPermission", - "azure.storage.fileshare._generated.operations.ShareOperations.get_permission": "Storage.File.Share.getPermission", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.get_permission": "Storage.File.Share.getPermission", - "azure.storage.fileshare._generated.operations.ShareOperations.set_properties": "Storage.File.Share.setProperties", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.set_properties": "Storage.File.Share.setProperties", - "azure.storage.fileshare._generated.operations.ShareOperations.set_metadata": "Storage.File.Share.setMetadata", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.set_metadata": "Storage.File.Share.setMetadata", - "azure.storage.fileshare._generated.operations.ShareOperations.get_access_policy": "Storage.File.Share.getAccessPolicy", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.get_access_policy": "Storage.File.Share.getAccessPolicy", - "azure.storage.fileshare._generated.operations.ShareOperations.set_access_policy": "Storage.File.Share.setAccessPolicy", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.set_access_policy": "Storage.File.Share.setAccessPolicy", - "azure.storage.fileshare._generated.operations.ShareOperations.get_statistics": "Storage.File.Share.getStatistics", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.get_statistics": "Storage.File.Share.getStatistics", - "azure.storage.fileshare._generated.operations.ShareOperations.restore": "Storage.File.Share.restore", - "azure.storage.fileshare._generated.aio.operations.ShareOperations.restore": "Storage.File.Share.restore", - "azure.storage.fileshare._generated.operations.DirectoryOperations.create": "Storage.File.Directory.create", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.create": "Storage.File.Directory.create", - "azure.storage.fileshare._generated.operations.DirectoryOperations.get_properties": "Storage.File.Directory.getProperties", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.get_properties": "Storage.File.Directory.getProperties", - "azure.storage.fileshare._generated.operations.DirectoryOperations.delete": "Storage.File.Directory.delete", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.delete": "Storage.File.Directory.delete", - "azure.storage.fileshare._generated.operations.DirectoryOperations.set_properties": "Storage.File.Directory.setProperties", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.set_properties": "Storage.File.Directory.setProperties", - "azure.storage.fileshare._generated.operations.DirectoryOperations.set_metadata": "Storage.File.Directory.setMetadata", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.set_metadata": "Storage.File.Directory.setMetadata", - "azure.storage.fileshare._generated.operations.DirectoryOperations.list_files_and_directories_segment": "Storage.File.Directory.listFilesAndDirectoriesSegment", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.list_files_and_directories_segment": "Storage.File.Directory.listFilesAndDirectoriesSegment", - "azure.storage.fileshare._generated.operations.DirectoryOperations.list_handles": "Storage.File.Directory.listHandles", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.list_handles": "Storage.File.Directory.listHandles", - "azure.storage.fileshare._generated.operations.DirectoryOperations.force_close_handles": "Storage.File.Directory.forceCloseHandles", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.force_close_handles": "Storage.File.Directory.forceCloseHandles", - "azure.storage.fileshare._generated.operations.DirectoryOperations.rename": "Storage.File.Directory.rename", - "azure.storage.fileshare._generated.aio.operations.DirectoryOperations.rename": "Storage.File.Directory.rename", - "azure.storage.fileshare._generated.operations.FileOperations.create": "Storage.File.File.create", - "azure.storage.fileshare._generated.aio.operations.FileOperations.create": "Storage.File.File.create", - "azure.storage.fileshare._generated.operations.FileOperations.download": "Storage.File.File.download", - "azure.storage.fileshare._generated.aio.operations.FileOperations.download": "Storage.File.File.download", - "azure.storage.fileshare._generated.operations.FileOperations.get_properties": "Storage.File.File.getProperties", - "azure.storage.fileshare._generated.aio.operations.FileOperations.get_properties": "Storage.File.File.getProperties", - "azure.storage.fileshare._generated.operations.FileOperations.delete": "Storage.File.File.delete", - "azure.storage.fileshare._generated.aio.operations.FileOperations.delete": "Storage.File.File.delete", - "azure.storage.fileshare._generated.operations.FileOperations.set_http_headers": "Storage.File.File.setHttpHeaders", - "azure.storage.fileshare._generated.aio.operations.FileOperations.set_http_headers": "Storage.File.File.setHttpHeaders", - "azure.storage.fileshare._generated.operations.FileOperations.set_metadata": "Storage.File.File.setMetadata", - "azure.storage.fileshare._generated.aio.operations.FileOperations.set_metadata": "Storage.File.File.setMetadata", - "azure.storage.fileshare._generated.operations.FileOperations.acquire_lease": "Storage.File.File.acquireLease", - "azure.storage.fileshare._generated.aio.operations.FileOperations.acquire_lease": "Storage.File.File.acquireLease", - "azure.storage.fileshare._generated.operations.FileOperations.release_lease": "Storage.File.File.releaseLease", - "azure.storage.fileshare._generated.aio.operations.FileOperations.release_lease": "Storage.File.File.releaseLease", - "azure.storage.fileshare._generated.operations.FileOperations.change_lease": "Storage.File.File.changeLease", - "azure.storage.fileshare._generated.aio.operations.FileOperations.change_lease": "Storage.File.File.changeLease", - "azure.storage.fileshare._generated.operations.FileOperations.break_lease": "Storage.File.File.breakLease", - "azure.storage.fileshare._generated.aio.operations.FileOperations.break_lease": "Storage.File.File.breakLease", - "azure.storage.fileshare._generated.operations.FileOperations.upload_range": "Storage.File.File.uploadRange", - "azure.storage.fileshare._generated.aio.operations.FileOperations.upload_range": "Storage.File.File.uploadRange", - "azure.storage.fileshare._generated.operations.FileOperations.upload_range_from_url": "Storage.File.File.uploadRangeFromUrl", - "azure.storage.fileshare._generated.aio.operations.FileOperations.upload_range_from_url": "Storage.File.File.uploadRangeFromUrl", - "azure.storage.fileshare._generated.operations.FileOperations.get_range_list": "Storage.File.File.getRangeList", - "azure.storage.fileshare._generated.aio.operations.FileOperations.get_range_list": "Storage.File.File.getRangeList", - "azure.storage.fileshare._generated.operations.FileOperations.start_copy": "Storage.File.File.startCopy", - "azure.storage.fileshare._generated.aio.operations.FileOperations.start_copy": "Storage.File.File.startCopy", - "azure.storage.fileshare._generated.operations.FileOperations.abort_copy": "Storage.File.File.abortCopy", - "azure.storage.fileshare._generated.aio.operations.FileOperations.abort_copy": "Storage.File.File.abortCopy", - "azure.storage.fileshare._generated.operations.FileOperations.list_handles": "Storage.File.File.listHandles", - "azure.storage.fileshare._generated.aio.operations.FileOperations.list_handles": "Storage.File.File.listHandles", - "azure.storage.fileshare._generated.operations.FileOperations.force_close_handles": "Storage.File.File.forceCloseHandles", - "azure.storage.fileshare._generated.aio.operations.FileOperations.force_close_handles": "Storage.File.File.forceCloseHandles", - "azure.storage.fileshare._generated.operations.FileOperations.rename": "Storage.File.File.rename", - "azure.storage.fileshare._generated.aio.operations.FileOperations.rename": "Storage.File.File.rename", - "azure.storage.fileshare._generated.operations.FileOperations.create_symbolic_link": "Storage.File.File.createSymbolicLink", - "azure.storage.fileshare._generated.aio.operations.FileOperations.create_symbolic_link": "Storage.File.File.createSymbolicLink", - "azure.storage.fileshare._generated.operations.FileOperations.get_symbolic_link": "Storage.File.File.getSymbolicLink", - "azure.storage.fileshare._generated.aio.operations.FileOperations.get_symbolic_link": "Storage.File.File.getSymbolicLink", - "azure.storage.fileshare._generated.operations.FileOperations.create_hard_link": "Storage.File.File.createHardLink", - "azure.storage.fileshare._generated.aio.operations.FileOperations.create_hard_link": "Storage.File.File.createHardLink" + "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/storage/fileshare/_generated/_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py index 7cd63e8440a5..6540b3fde6f6 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py @@ -25,14 +25,14 @@ 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 service: ServiceOperations operations - :vartype service: azure.storage.fileshare._generated.operations.ServiceOperations - :ivar share: ShareOperations operations - :vartype share: azure.storage.fileshare._generated.operations.ShareOperations :ivar directory: DirectoryOperations operations - :vartype directory: azure.storage.fileshare._generated.operations.DirectoryOperations + :vartype directory: azure.storage.fileshare.operations.DirectoryOperations :ivar file: FileOperations operations - :vartype file: azure.storage.fileshare._generated.operations.FileOperations + :vartype file: azure.storage.fileshare.operations.FileOperations + :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 @@ -70,10 +70,10 @@ def __init__(self, url: str, credential: "TokenCredential", **kwargs: Any) -> No 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: """Runs the network request through the client's chained policies. 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 index a75a22adbb97..eef4e52ed1a0 100644 --- 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 @@ -600,57 +600,9 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: for rest_field in self._attr_to_rest_field.values() if rest_field._default is not _UNSET } - if args: # pylint: disable=too-many-nested-blocks + if args: if isinstance(args[0], ET.Element): - existed_attr_keys = [] - model_meta = getattr(self, "_xml", {}) - - 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 = prop_meta.get("ns", model_meta.get("ns", None)) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - if prop_meta.get("itemsName"): - xml_name = prop_meta.get("itemsName") - xml_ns = prop_meta.get("itemNs") - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = args[0].findall(xml_name) # pyright: ignore - if len(items) > 0: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = [] - continue - - # text element is primitive type - if prop_meta.get("text", False): - if args[0].text is not None: - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = args[0].find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) - - # rest thing is additional properties - for e in args[0]: - if e.tag not in existed_attr_keys: - dict_to_pass[e.tag] = _convert_element(e) + 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()} @@ -669,6 +621,69 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> 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__) @@ -735,7 +750,7 @@ def _deserialize(cls, data, exist_discriminators): model_meta = getattr(cls, "_xml", {}) prop_meta = getattr(discriminator, "_xml", {}) xml_name = prop_meta.get("name", discriminator._rest_name) - xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) if xml_ns: xml_name = "{" + xml_ns + "}" + xml_name @@ -1208,6 +1223,56 @@ def serialize_xml(model: Model, exclude_readonly: bool = False) -> 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, @@ -1219,10 +1284,16 @@ def _get_element( # 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( - model_meta.get("name", o.__class__.__name__), + element_name, model_meta.get("prefix"), - model_meta.get("ns"), + _model_ns, ) readonly_props = [] @@ -1244,7 +1315,9 @@ def _get_element( # additional properties will not have rest field, use the wire name as xml name prop_meta = {"name": k} - # if no ns for prop, use model's + # 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") @@ -1256,12 +1329,7 @@ def _get_element( # text could only set on primitive type wrapped_element.text = _get_primitive_type_value(v) elif prop_meta.get("attribute", False): - xml_name = prop_meta.get("name", k) - if prop_meta.get("ns"): - ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore - xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore - # attribute should be primitive type - wrapped_element.set(xml_name, _get_primitive_type_value(v)) + _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)) @@ -1270,6 +1338,7 @@ def _get_element( 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( @@ -1277,7 +1346,7 @@ def _get_element( exclude_readonly, { "name": k, - "ns": parent_meta.get("ns") if parent_meta else None, + "ns": _dict_ns, "prefix": parent_meta.get("prefix") if parent_meta else None, }, ) @@ -1286,13 +1355,16 @@ def _get_element( # 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": parent_meta.get("itemsNs", parent_meta.get("ns")), + "ns": _items_ns, }, ) @@ -1304,8 +1376,9 @@ def _get_wrapped_element( 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.get("ns") if meta else None + 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)) @@ -1326,11 +1399,29 @@ def _get_primitive_type_value(v) -> str: 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: - ET.register_namespace(prefix, ns) + _safe_register_namespace(prefix, ns) if ns: return ET.Element("{" + ns + "}" + tag) return ET.Element(tag) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py index 5d099a8eefa8..cbe7736f7651 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py @@ -25,14 +25,14 @@ 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 service: ServiceOperations operations - :vartype service: azure.storage.fileshare._generated.aio.operations.ServiceOperations - :ivar share: ShareOperations operations - :vartype share: azure.storage.fileshare._generated.aio.operations.ShareOperations :ivar directory: DirectoryOperations operations - :vartype directory: azure.storage.fileshare._generated.aio.operations.DirectoryOperations + :vartype directory: azure.storage.fileshare.aio.operations.DirectoryOperations :ivar file: FileOperations operations - :vartype file: azure.storage.fileshare._generated.aio.operations.FileOperations + :vartype file: azure.storage.fileshare.aio.operations.FileOperations + :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 @@ -70,10 +70,10 @@ def __init__(self, url: str, credential: "AsyncTokenCredential", **kwargs: Any) 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 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 51785ce60910..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 @@ -12,20 +12,20 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import ServiceOperations # type: ignore -from ._operations import ShareOperations # 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/_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/operations/_operations.py index 1b86c0b51344..102996e2c972 100644 --- 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 @@ -90,14 +90,14 @@ JSON = MutableMapping[str, Any] -class ServiceOperations: +class DirectoryOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare._generated.aio.FileClient`'s - :attr:`service` attribute. + :class:`~azure.storage.fileshare.aio.FileClient`'s + :attr:`directory` attribute. """ def __init__(self, *args, **kwargs) -> None: @@ -108,25 +108,75 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - async def set_properties( + async def create( # pylint: disable=too-many-locals self, - storage_service_properties: _models.StorageServiceProperties, *, 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: - """Sets properties for a storage account's File service endpoint, including properties for Storage - Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. + """Creates a new directory under the specified share or parent directory. - :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 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._generated.models.ShareTokenIntent + :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: @@ -139,20 +189,28 @@ async def set_properties( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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( + _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, - content_type=content_type, + owner=owner, + group=group, + file_mode=file_mode, + file_property_semantics=file_property_semantics, + allow_trailing_dot=allow_trailing_dot, version=self._config.version, - content=_content, headers=_headers, params=_params, ) @@ -168,7 +226,7 @@ async def set_properties( response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -177,6 +235,32 @@ async def set_properties( 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( @@ -191,21 +275,27 @@ async def set_properties( 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 - ) -> _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. + ) -> 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._generated.models.ShareTokenIntent - :return: StorageServiceProperties. The StorageServiceProperties is compatible with - MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.StorageServiceProperties + :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 = { @@ -219,11 +309,13 @@ async def get_properties( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.StorageServiceProperties] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_service_get_properties_request( + _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, @@ -233,8 +325,7 @@ async def get_properties( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -242,11 +333,6 @@ async def get_properties( 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, @@ -255,58 +341,64 @@ async def get_properties( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def list_shares_segment( + async def delete( 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any - ) -> _models.ListSharesResponse: - """The List Shares Segment operation returns a list of the shares and share snapshots under the - specified account. + ) -> None: + """Removes the specified empty directory. Note that the directory must be empty before it can be + deleted. - :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._generated.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._generated.models.ListSharesIncludeType] - :return: ListSharesResponse. The ListSharesResponse is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ListSharesResponse + :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 = { @@ -320,15 +412,12 @@ async def list_shares_segment( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListSharesResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_service_list_shares_segment_request( - prefix=prefix, - marker=marker, - maxresults=maxresults, + _request = build_directory_delete_request( timeout=timeout, file_request_intent=file_request_intent, - include=include, + allow_trailing_dot=allow_trailing_dot, version=self._config.version, headers=_headers, params=_params, @@ -338,20 +427,14 @@ async def list_shares_segment( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + 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, @@ -366,31 +449,74 @@ async def list_shares_segment( "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 + return cls(pipeline_response, None, response_headers) # 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 + 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,19 +527,26 @@ async def get_user_delegation_key( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_service_get_user_delegation_key_request( + _request = build_directory_set_properties_request( timeout=timeout, - content_type=content_type, + 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, - content=_content, headers=_headers, params=_params, ) @@ -422,8 +555,7 @@ async def get_user_delegation_key( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -431,11 +563,6 @@ async def get_user_delegation_key( 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, @@ -444,105 +571,62 @@ async def get_user_delegation_key( 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")) - 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._generated.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") + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def create( # pylint: disable=too-many-locals + async def set_metadata( 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, + allow_trailing_dot: Optional[bool] = 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. + """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 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._generated.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._generated.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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -560,21 +644,11 @@ async def create( # pylint: disable=too-many-locals cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_create_request( + _request = build_directory_set_metadata_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, + allow_trailing_dot=allow_trailing_dot, 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, @@ -591,7 +665,7 @@ async def create( # pylint: disable=too-many-locals response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -601,19 +675,8 @@ async def create( # pylint: disable=too-many-locals 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-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") ) 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")) @@ -626,31 +689,49 @@ async def create( # pylint: disable=too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_properties( + 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, - lease_id: Optional[str] = None, **kwargs: Any - ) -> None: - """Returns all user-defined metadata and system properties for the specified share or share - snapshot. + ) -> _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 file_request_intent: Valid values are 'backup'. "backup" Default value is None. - :paramtype file_request_intent: str or - ~azure.storage.fileshare._generated.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 + :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 = { @@ -664,13 +745,18 @@ async def get_properties( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ListFilesAndDirectoriesSegmentResponse] = kwargs.pop("cls", None) - _request = build_share_get_properties_request( + _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, - lease_id=lease_id, version=self._config.version, headers=_headers, params=_params, @@ -680,7 +766,8 @@ async def get_properties( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 ) @@ -688,6 +775,11 @@ async def get_properties( 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, @@ -696,107 +788,59 @@ async def get_properties( 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( - "str", 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def delete( + async def list_handles( self, *, - sharesnapshot: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, timeout: Optional[int] = None, - delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = 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. + ) -> _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 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._generated.models.DeleteSnapshotsOptionType + :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._generated.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 + :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 = { @@ -810,14 +854,16 @@ async def delete( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) - _request = build_share_delete_request( - sharesnapshot=sharesnapshot, + _request = build_directory_list_handles_request( + marker=marker, + maxresults=maxresults, timeout=timeout, - delete_snapshots=delete_snapshots, + sharesnapshot=sharesnapshot, + recursive=recursive, + allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, - lease_id=lease_id, version=self._config.version, headers=_headers, params=_params, @@ -827,14 +873,20 @@ async def delete( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [202]: + 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, @@ -843,52 +895,58 @@ async def delete( 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def acquire_lease( + async def force_close_handles( self, *, + handle_id: str, timeout: Optional[int] = None, - lease_duration: Optional[int] = None, - proposed_lease_id: Optional[str] = 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: - """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. + """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 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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -904,16 +962,16 @@ async def acquire_lease( _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( + _request = build_directory_force_close_handles_request( + handle_id=handle_id, timeout=timeout, - lease_duration=lease_duration, - proposed_lease_id=proposed_lease_id, + marker=marker, sharesnapshot=sharesnapshot, + recursive=recursive, + allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, - action=action, version=self._config.version, headers=_headers, params=_params, @@ -930,7 +988,7 @@ async def acquire_lease( response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -939,9 +997,13 @@ async def acquire_lease( 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-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( @@ -953,28 +1015,75 @@ async def acquire_lease( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def release_lease( + async def rename( # pylint: disable=too-many-locals self, *, - lease_id: str, + rename_source: str, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = 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: - """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. + """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 lease_id: Specifies the current lease ID on the resource. Required. - :paramtype lease_id: str + :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 sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a - share snapshot. Default value is None. - :paramtype sharesnapshot: str + :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -990,15 +1099,26 @@ async def release_lease( _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, + _request = build_directory_rename_request( + rename_source=rename_source, timeout=timeout, - sharesnapshot=sharesnapshot, + 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, - action=action, version=self._config.version, headers=_headers, params=_params, @@ -1026,6 +1146,26 @@ async def release_lease( 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( @@ -1036,34 +1176,152 @@ async def release_lease( 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 change_lease( + async def create( # pylint: disable=too-many-locals self, + optional_body: Optional[bytes] = None, *, - lease_id: str, - proposed_lease_id: Optional[str] = None, + content_length: int, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = 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, + optional_content_length: Optional[int] = None, + structured_body_type: Optional[str] = None, + structured_content_length: Optional[int] = 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. + """Creates a new file or replaces a file. Note it only initializes the file with no content. - :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 + :param optional_body: Initial data. Default value is None. + :type optional_body: bytes + :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. + Required. + :paramtype content_length: 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 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._generated.models.ShareTokenIntent + :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 optional_content_length: Optional. Specifies the content length of the file. Default + value is None. + :paramtype optional_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: @@ -1076,20 +1334,51 @@ async def change_lease( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + 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) - _request = build_share_change_lease_request( - lease_id=lease_id, - proposed_lease_id=proposed_lease_id, + _content = optional_body + + _request = build_file_create_request( + content_length=content_length, timeout=timeout, - sharesnapshot=sharesnapshot, + 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, - action=action, + owner=owner, + group=group, + file_mode=file_mode, + nfs_file_type=nfs_file_type, + content_md5=content_md5, + file_property_semantics=file_property_semantics, + optional_content_length=optional_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, ) @@ -1102,21 +1391,49 @@ async def change_lease( 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 = 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( @@ -1128,30 +1445,42 @@ async def change_lease( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def renew_lease( + async def download( self, *, - lease_id: str, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = 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 - ) -> 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. + ) -> AsyncIterator[bytes]: + """Reads or downloads a file from the system, including its metadata and properties. - :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 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._generated.models.ShareTokenIntent - :return: None - :rtype: 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 = { @@ -1165,15 +1494,16 @@ async def renew_lease( _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) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _request = build_share_renew_lease_request( - lease_id=lease_id, + _request = build_file_download_request( timeout=timeout, - sharesnapshot=sharesnapshot, + 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, - action=action, + structured_body_type=structured_body_type, version=self._config.version, headers=_headers, params=_params, @@ -1183,14 +1513,20 @@ async def renew_lease( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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]: + 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, @@ -1199,54 +1535,106 @@ async def renew_lease( raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["Last-Modified"] = self._deserialize("str", 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["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["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( + "str", 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-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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def break_lease( + async def get_properties( self, *, + sharesnapshot: Optional[str] = None, timeout: Optional[int] = None, - break_period: Optional[int] = None, lease_id: 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: - """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. + ) -> 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 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 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._generated.models.ShareTokenIntent - :return: None - :rtype: None + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1260,16 +1648,14 @@ async def break_lease( _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( + _request = build_file_get_properties_request( + sharesnapshot=sharesnapshot, timeout=timeout, - break_period=break_period, lease_id=lease_id, - sharesnapshot=sharesnapshot, + allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, - action=action, version=self._config.version, headers=_headers, params=_params, @@ -1286,7 +1672,7 @@ async def break_lease( response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -1295,10 +1681,55 @@ async def break_lease( raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["Last-Modified"] = self._deserialize("str", 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["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["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( + "str", 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( @@ -1308,25 +1739,30 @@ async def break_lease( if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace_async - async def create_snapshot( + async def delete( self, *, 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 ) -> None: - """Creates a read-only snapshot of a share. + """Removes the file from the storage account. :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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -1344,9 +1780,10 @@ async def create_snapshot( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_create_snapshot_request( + _request = build_file_delete_request( timeout=timeout, - metadata=metadata, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, version=self._config.version, headers=_headers, @@ -1364,7 +1801,7 @@ async def create_snapshot( response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -1373,9 +1810,7 @@ async def create_snapshot( 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-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( @@ -1386,111 +1821,100 @@ async def create_snapshot( 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._generated.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._generated.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._generated.models.ShareTokenIntent - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace_async - async def create_permission( + async def set_http_headers( # pylint: disable=too-many-locals self, - permission: Union[_models.SharePermission, JSON, IO[bytes]], *, 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: - """Create a permission (a security descriptor). This is used to support file level ACLs for SMB - shares. + """Sets HTTP headers on a file. - :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_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._generated.models.ShareTokenIntent + :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: @@ -1503,25 +1927,34 @@ async def create_permission( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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( + _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, - content_type=content_type, + owner=owner, + group=group, + file_mode=file_mode, version=self._config.version, - content=_content, headers=_headers, params=_params, ) @@ -1537,7 +1970,7 @@ async def create_permission( response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -1546,9 +1979,32 @@ async def create_permission( 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( @@ -1560,33 +2016,32 @@ async def create_permission( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_permission( + async def set_metadata( self, *, - file_permission_key: str, timeout: Optional[int] = None, - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = 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 - ) -> _models.SharePermission: - """Returns the permission (security descriptor) for a given permission key. This is used to - support file level ACLs for SMB shares. + ) -> None: + """Sets one or more user-defined name-value pairs for the specified file. - :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 + :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 file_permission_format: str or - ~azure.storage.fileshare._generated.models.FilePermissionFormat + :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._generated.models.ShareTokenIntent - :return: SharePermission. The SharePermission is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.SharePermission + :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 = { @@ -1600,13 +2055,14 @@ async def get_permission( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.SharePermission] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_get_permission_request( - file_permission_key=file_permission_key, + _request = build_file_set_metadata_request( timeout=timeout, - file_permission_format=file_permission_format, + 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, @@ -1616,8 +2072,7 @@ async def get_permission( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1625,11 +2080,6 @@ async def get_permission( 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, @@ -1638,84 +2088,49 @@ async def get_permission( 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["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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def set_properties( # pylint: disable=too-many-locals + async def acquire_lease( 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, + lease_duration: Optional[int] = None, + proposed_lease_id: Optional[str] = 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> None: - """Sets properties for the specified share. + """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 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._generated.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._generated.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 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._generated.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 + :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: @@ -1731,22 +2146,16 @@ async def set_properties( # pylint: disable=too-many-locals _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_set_properties_request( + _request = build_file_acquire_lease_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, + lease_duration=lease_duration, + proposed_lease_id=proposed_lease_id, 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, + allow_trailing_dot=allow_trailing_dot, + action=action, version=self._config.version, headers=_headers, params=_params, @@ -1763,7 +2172,7 @@ async def set_properties( # pylint: disable=too-many-locals response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -1774,28 +2183,7 @@ async def set_properties( # pylint: disable=too-many-locals 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-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( @@ -1807,27 +2195,27 @@ async def set_properties( # pylint: disable=too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def set_metadata( + async def release_lease( self, *, + lease_id: 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> None: - """Sets one or more user-defined name-value pairs for the specified share. + """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 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._generated.models.ShareTokenIntent + :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: @@ -1843,13 +2231,15 @@ async def set_metadata( _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_set_metadata_request( - timeout=timeout, - metadata=metadata, + _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, @@ -1888,27 +2278,34 @@ async def set_metadata( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_access_policy( + async def change_lease( self, *, + lease_id: str, timeout: Optional[int] = None, - lease_id: Optional[str] = None, + proposed_lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any - ) -> _models.SignedIdentifiers: - """Returns information about stored access policies specified on the share that may be used with - Shared Access Signatures. + ) -> 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 lease_id: If specified, the lease ID must match the lease ID of the file. Default - value is None. - :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 file_request_intent: Valid values are 'backup'. "backup" Default value is None. - :paramtype file_request_intent: str or - ~azure.storage.fileshare._generated.models.ShareTokenIntent - :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.SignedIdentifiers + :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 = { @@ -1922,12 +2319,16 @@ async def get_access_policy( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_get_access_policy_request( - timeout=timeout, + _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, @@ -1937,8 +2338,7 @@ async def get_access_policy( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -1946,11 +2346,6 @@ async def get_access_policy( 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, @@ -1961,46 +2356,40 @@ async def get_access_policy( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def set_access_policy( + async def break_lease( 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> None: - """Sets stored access policies for the share that may be used with Shared Access Signatures. + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. - :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._generated.models.ShareTokenIntent + :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: @@ -2013,25 +2402,19 @@ async def set_access_policy( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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 + action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) 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( + _request = build_file_break_lease_request( timeout=timeout, lease_id=lease_id, file_request_intent=file_request_intent, - content_type=content_type, + allow_trailing_dot=allow_trailing_dot, + action=action, version=self._config.version, - content=_content, headers=_headers, params=_params, ) @@ -2047,7 +2430,7 @@ async def set_access_policy( response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -2058,6 +2441,8 @@ async def set_access_policy( 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( @@ -2069,26 +2454,63 @@ async def set_access_policy( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_statistics( + 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 - ) -> _models.ShareStats: - """Retrieves statistics related to the share. + ) -> 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._generated.models.ShareTokenIntent - :return: ShareStats. The ShareStats is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ShareStats + :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 = { @@ -2099,16 +2521,32 @@ async def get_statistics( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ShareStats] = kwargs.pop("cls", None) + 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) - _request = build_share_get_statistics_request( + _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, ) @@ -2117,20 +2555,14 @@ async def get_statistics( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + 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, @@ -2141,47 +2573,90 @@ async def get_statistics( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def restore( + 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, - deleted_share_name: Optional[str] = None, - deleted_share_version: Optional[str] = None, + source_content_crc64: Optional[str] = None, + source_if_match_crc64: Optional[str] = None, + source_if_none_match_crc64: Optional[str] = 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: - """Restores a previously deleted share. + """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 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 + :keyword source_content_crc64: Specify the CRC64 hash of the source content. Default value is + None. + :paramtype source_content_crc64: str + :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: str + :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: str + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default value is None. - :paramtype deleted_share_version: str + :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2199,10 +2674,21 @@ async def restore( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_restore_request( + _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, - deleted_share_name=deleted_share_name, - deleted_share_version=deleted_share_version, + 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, @@ -2231,18 +2717,12 @@ async def restore( 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-content-crc64"] = self._deserialize("str", 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-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + 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")) @@ -2254,98 +2734,46 @@ async def restore( if cls: return cls(pipeline_response, None, response_headers) # type: ignore - -class DirectoryOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare._generated.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 + async def get_range_list( 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 + *, + 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 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._generated.models.FilePermissionFormat - :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. - :paramtype file_request_intent: str or - ~azure.storage.fileshare._generated.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._generated.models.FilePropertySemantics + :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 - :return: None - :rtype: None + :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 = { @@ -2359,24 +2787,17 @@ async def create( # pylint: disable=too-many-locals _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ShareFileRangeList] = kwargs.pop("cls", None) - _request = build_directory_create_request( + _request = build_file_get_range_list_request( + sharesnapshot=sharesnapshot, + prevsharesnapshot=prevsharesnapshot, 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, + 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, @@ -2386,14 +2807,20 @@ async def create( # pylint: disable=too-many-locals } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [201]: + 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, @@ -2402,66 +2829,118 @@ async def create( # pylint: disable=too-many-locals 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["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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def get_properties( + async def start_copy( # pylint: disable=too-many-locals self, *, - sharesnapshot: Optional[str] = None, + copy_source: str, timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = 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: - """Returns all system properties for the specified directory, and can also be used to check the - existence of a directory. + """Copies a blob or file to a destination file within the storage account. - :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a - share snapshot. Default value is None. - :paramtype sharesnapshot: 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 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._generated.models.ShareTokenIntent + :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: @@ -2479,11 +2958,29 @@ async def get_properties( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_get_properties_request( - sharesnapshot=sharesnapshot, + _request = build_file_start_copy_request( + copy_source=copy_source, timeout=timeout, - file_request_intent=file_request_intent, + 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, @@ -2500,42 +2997,19 @@ async def get_properties( response = pipeline_response.http_response - if response.status_code not in [200]: + 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-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 = {} + 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( @@ -2547,25 +3021,32 @@ async def get_properties( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def delete( + async def abort_copy( self, *, + copyid: str, timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = 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 specified empty directory. Note that the directory must be empty before it can be - deleted. + """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 file_request_intent: Valid values are 'backup'. "backup" Default value is None. - :paramtype file_request_intent: str or - ~azure.storage.fileshare._generated.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 :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: @@ -2581,12 +3062,18 @@ async def delete( _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_directory_delete_request( + _request = build_file_abort_copy_request( + copyid=copyid, timeout=timeout, - file_request_intent=file_request_intent, + 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, @@ -2603,7 +3090,7 @@ async def delete( response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -2623,71 +3110,36 @@ async def delete( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def set_properties( # pylint: disable=too-many-locals + async def list_handles( self, *, + marker: Optional[str] = None, + maxresults: Optional[int] = None, 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, + sharesnapshot: 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 properties for the specified directory. + ) -> _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 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._generated.models.FilePermissionFormat + :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._generated.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 + :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 = { @@ -2701,22 +3153,15 @@ async def set_properties( # pylint: disable=too-many-locals _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) - _request = build_directory_set_properties_request( + _request = build_file_list_handles_request( + marker=marker, + maxresults=maxresults, 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, + sharesnapshot=sharesnapshot, 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, @@ -2726,7 +3171,8 @@ async def set_properties( # pylint: disable=too-many-locals } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 ) @@ -2734,6 +3180,11 @@ async def set_properties( # pylint: disable=too-many-locals 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, @@ -2742,63 +3193,54 @@ async def set_properties( # pylint: disable=too-many-locals 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def set_metadata( + async def force_close_handles( self, *, + handle_id: str, timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = 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: - """Sets one or more user-defined name-value pairs for the specified directory. + """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 metadata: Optional. User-defined metadata for the resource. Default value is None. - :paramtype metadata: dict[str, 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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2816,9 +3258,11 @@ async def set_metadata( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_set_metadata_request( + _request = build_file_force_close_handles_request( + handle_id=handle_id, timeout=timeout, - metadata=metadata, + marker=marker, + sharesnapshot=sharesnapshot, allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, version=self._config.version, @@ -2846,9 +3290,12 @@ async def set_metadata( 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["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")) @@ -2861,51 +3308,80 @@ async def set_metadata( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def list_files_and_directories_segment( + async def rename( # pylint: disable=too-many-locals 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, + rename_source: str, timeout: Optional[int] = None, - include_extended_info: Optional[bool] = 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 - ) -> _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. + ) -> 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 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._generated.models.ListFilesIncludeType] + :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 include_extended_info: Include extended information. Default value is None. - :paramtype include_extended_info: bool + :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._generated.models.ShareTokenIntent - :return: ListFilesAndDirectoriesSegmentResponse. The ListFilesAndDirectoriesSegmentResponse is - compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ListFilesAndDirectoriesSegmentResponse + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2919,17 +3395,26 @@ async def list_files_and_directories_segment( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListFilesAndDirectoriesSegmentResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_list_files_and_directories_segment_request( - prefix=prefix, - sharesnapshot=sharesnapshot, - marker=marker, - maxresults=maxresults, - include=include, + _request = build_file_rename_request( + rename_source=rename_source, timeout=timeout, - include_extended_info=include_extended_info, + 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, @@ -2940,8 +3425,7 @@ async def list_files_and_directories_segment( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2949,11 +3433,6 @@ async def list_files_and_directories_segment( 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, @@ -2962,60 +3441,78 @@ async def list_files_and_directories_segment( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def list_handles( + async def create_symbolic_link( self, *, - marker: Optional[str] = None, - maxresults: Optional[int] = None, + link_text: str, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - recursive: Optional[bool] = None, - allow_trailing_dot: Optional[bool] = 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 - ) -> _models.ListHandlesResponse: - """Lists handles for directory. + ) -> None: + """Creates a symbolic link to a target file. NFS only. - :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 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 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 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._generated.models.ShareTokenIntent - :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3029,15 +3526,17 @@ async def list_handles( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_list_handles_request( - marker=marker, - maxresults=maxresults, + _request = build_file_create_symbolic_link_request( + link_text=link_text, timeout=timeout, - sharesnapshot=sharesnapshot, - recursive=recursive, - allow_trailing_dot=allow_trailing_dot, + 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, @@ -3048,20 +3547,14 @@ async def list_handles( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + 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, @@ -3070,59 +3563,51 @@ async def list_handles( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def force_close_handles( + async def get_symbolic_link( 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. + """Returns the target of a symbolic link. NFS only. - :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3140,13 +3625,9 @@ async def force_close_handles( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_force_close_handles_request( - handle_id=handle_id, + _request = build_file_get_symbolic_link_request( 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, @@ -3173,95 +3654,41 @@ async def force_close_handles( 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["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 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, + + 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: - """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. + """Creates a hard link to a target file. NFS only. - :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 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 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 + :keyword lease_id: If specified, the lease ID must match the lease ID of 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._generated.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 + :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3277,26 +3704,15 @@ async def rename( # pylint: disable=too-many-locals _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_directory_rename_request( - rename_source=rename_source, + _request = build_file_create_hard_link_request( + target_file=target_file, 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, + lease_id=lease_id, file_request_intent=file_request_intent, + file_type=file_type, version=self._config.version, headers=_headers, params=_params, @@ -3313,7 +3729,7 @@ async def rename( # pylint: disable=too-many-locals response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -3324,15 +3740,6 @@ async def rename( # pylint: disable=too-many-locals 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") ) @@ -3344,6 +3751,11 @@ async def rename( # pylint: disable=too-many-locals ) 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( @@ -3355,14 +3767,14 @@ async def rename( # pylint: disable=too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore -class FileOperations: # pylint: disable=too-many-public-methods +class ServiceOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare._generated.aio.FileClient`'s - :attr:`file` attribute. + :class:`~azure.storage.fileshare.aio.FileClient`'s + :attr:`service` attribute. """ def __init__(self, *args, **kwargs) -> None: @@ -3373,135 +3785,24 @@ def __init__(self, *args, **kwargs) -> None: 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 + async def set_properties( self, - optional_body: Optional[bytes] = None, + storage_service_properties: _models.StorageServiceProperties, *, - 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, - optional_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. + """Sets properties for a storage account's File service endpoint, including properties for Storage + Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. - :param optional_body: Initial data. Default value is None. - :type optional_body: bytes - :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. - Required. - :paramtype content_length: int + :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_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._generated.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._generated.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._generated.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._generated.models.FilePropertySemantics - :keyword optional_content_length: Optional. Specifies the content length of the file. Default - value is None. - :paramtype optional_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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3517,45 +3818,14 @@ async def create( # pylint: disable=too-many-locals _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 + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) cls: ClsType[None] = kwargs.pop("cls", None) - _content = optional_body + _content = _get_element(storage_service_properties) - _request = build_file_create_request( - content_length=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, - optional_content_length=optional_content_length, - structured_body_type=structured_body_type, - structured_content_length=structured_content_length, - file_type=file_type, + _request = build_service_set_properties_request( + timeout=timeout, + file_request_intent=file_request_intent, content_type=content_type, version=self._config.version, content=_content, @@ -3574,7 +3844,7 @@ async def create( # pylint: disable=too-many-locals response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -3583,37 +3853,6 @@ async def create( # pylint: disable=too-many-locals 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( @@ -3625,43 +3864,23 @@ async def create( # pylint: disable=too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def download( + async def get_properties( 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. + ) -> _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 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._generated.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] + :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 = { @@ -3675,16 +3894,11 @@ async def download( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + cls: ClsType[_models.StorageServiceProperties] = kwargs.pop("cls", None) - _request = build_file_download_request( + _request = build_service_get_properties_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, @@ -3695,14 +3909,14 @@ async def download( _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", 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, 206]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -3716,62 +3930,6 @@ async def download( raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["Last-Modified"] = self._deserialize("str", 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( - "str", 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-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( @@ -3780,7 +3938,10 @@ async def download( 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 _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 @@ -3788,35 +3949,37 @@ async def download( return deserialized # type: ignore @distributed_trace_async - async def get_properties( + async def list_shares_segment( self, *, - sharesnapshot: Optional[str] = None, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = 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, + include: Optional[list[Union[str, _models.ListSharesIncludeType]]] = None, **kwargs: Any - ) -> bool: - """Returns all user-defined metadata, standard HTTP properties, and system properties for the - file. + ) -> _models.ListSharesResponse: + """The List Shares Segment operation returns a list of the shares and share snapshots under the + specified account. - :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a - share snapshot. Default value is None. - :paramtype sharesnapshot: str + :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 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._generated.models.ShareTokenIntent - :return: bool - :rtype: bool + :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 = { @@ -3830,14 +3993,15 @@ async def get_properties( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ListSharesResponse] = kwargs.pop("cls", None) - _request = build_file_get_properties_request( - sharesnapshot=sharesnapshot, + _request = build_service_list_shares_segment_request( + prefix=prefix, + marker=marker, + maxresults=maxresults, timeout=timeout, - lease_id=lease_id, - allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, + include=include, version=self._config.version, headers=_headers, params=_params, @@ -3847,107 +4011,59 @@ async def get_properties( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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]: - 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("str", 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( - "str", 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 = 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, None, response_headers) # type: ignore - return 200 <= response.status_code <= 299 + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @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. + 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 - :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._generated.models.ShareTokenIntent - :return: None - :rtype: None + :return: UserDelegationKey. The UserDelegationKey is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.UserDelegationKey :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3958,17 +4074,19 @@ async def delete( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) - _request = build_file_delete_request( + _content = _get_element(key_info) + + _request = build_service_get_user_delegation_key_request( timeout=timeout, - lease_id=lease_id, - allow_trailing_dot=allow_trailing_dot, - file_request_intent=file_request_intent, + content_type=content_type, version=self._config.version, + content=_content, headers=_headers, params=_params, ) @@ -3977,14 +4095,20 @@ async def delete( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [202]: + 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, @@ -3993,113 +4117,104 @@ async def delete( 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")) + 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, None, response_headers) # type: ignore + 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 set_http_headers( # pylint: disable=too-many-locals + async def create( # 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, + 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, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = 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 HTTP headers on a file. + """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 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 + :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 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 + :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 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._generated.models.FilePermissionFormat - :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + :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 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._generated.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 + :paramtype enable_smb_directory_lease: bool :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4117,28 +4232,21 @@ async def set_http_headers( # pylint: disable=too-many-locals cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_set_http_headers_request( + _request = build_share_create_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, + 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, - owner=owner, - group=group, - file_mode=file_mode, + 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, @@ -4155,7 +4263,7 @@ async def set_http_headers( # pylint: disable=too-many-locals response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -4166,30 +4274,19 @@ async def set_http_headers( # pylint: disable=too-many-locals 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-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-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-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-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") + 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-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( @@ -4201,31 +4298,28 @@ async def set_http_headers( # pylint: disable=too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def set_metadata( + async def get_properties( self, *, + sharesnapshot: Optional[str] = None, 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, + lease_id: Optional[str] = None, **kwargs: Any ) -> None: - """Sets one or more user-defined name-value pairs for the specified file. + """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 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 :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._generated.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: @@ -4243,12 +4337,11 @@ async def set_metadata( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_set_metadata_request( + _request = build_share_get_properties_request( + sharesnapshot=sharesnapshot, timeout=timeout, - metadata=metadata, - lease_id=lease_id, file_request_intent=file_request_intent, - allow_trailing_dot=allow_trailing_dot, + lease_id=lease_id, version=self._config.version, headers=_headers, params=_params, @@ -4274,9 +4367,65 @@ async def set_metadata( 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["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-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( + "str", 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")) @@ -4289,35 +4438,32 @@ async def set_metadata( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def acquire_lease( + async def delete( self, *, + sharesnapshot: Optional[str] = None, timeout: Optional[int] = None, - lease_duration: Optional[int] = None, - proposed_lease_id: Optional[str] = None, + delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - allow_trailing_dot: Optional[bool] = None, + lease_id: Optional[str] = None, **kwargs: Any ) -> None: - """The Lease File operation establishes and manages a lock on a file for write and delete - operations. + """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 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 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._generated.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 + :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: @@ -4333,16 +4479,14 @@ async def acquire_lease( _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( + _request = build_share_delete_request( + sharesnapshot=sharesnapshot, timeout=timeout, - lease_duration=lease_duration, - proposed_lease_id=proposed_lease_id, + delete_snapshots=delete_snapshots, file_request_intent=file_request_intent, - allow_trailing_dot=allow_trailing_dot, - action=action, + lease_id=lease_id, version=self._config.version, headers=_headers, params=_params, @@ -4359,7 +4503,7 @@ async def acquire_lease( response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -4368,9 +4512,12 @@ async def acquire_lease( 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-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( @@ -4382,28 +4529,34 @@ async def acquire_lease( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def release_lease( + async def acquire_lease( self, *, - lease_id: str, 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, - 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. + """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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4419,14 +4572,15 @@ async def release_lease( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) + action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_release_lease_request( - lease_id=lease_id, + _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, - allow_trailing_dot=allow_trailing_dot, action=action, version=self._config.version, headers=_headers, @@ -4444,7 +4598,7 @@ async def release_lease( response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -4455,6 +4609,7 @@ async def release_lease( 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( @@ -4466,33 +4621,27 @@ async def release_lease( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def change_lease( + async def release_lease( self, *, lease_id: str, timeout: Optional[int] = None, - proposed_lease_id: Optional[str] = None, + sharesnapshot: 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. + """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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4508,15 +4657,14 @@ async def change_lease( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_change_lease_request( + _request = build_share_release_lease_request( lease_id=lease_id, timeout=timeout, - proposed_lease_id=proposed_lease_id, + sharesnapshot=sharesnapshot, file_request_intent=file_request_intent, - allow_trailing_dot=allow_trailing_dot, action=action, version=self._config.version, headers=_headers, @@ -4545,7 +4693,6 @@ async def change_lease( 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( @@ -4557,29 +4704,32 @@ async def change_lease( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def break_lease( + async def change_lease( self, *, + lease_id: str, + proposed_lease_id: Optional[str] = None, timeout: Optional[int] = None, - lease_id: Optional[str] = None, + sharesnapshot: 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. + """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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4595,14 +4745,15 @@ async def break_lease( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_break_lease_request( - timeout=timeout, + _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, - allow_trailing_dot=allow_trailing_dot, action=action, version=self._config.version, headers=_headers, @@ -4620,7 +4771,7 @@ async def break_lease( response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -4631,7 +4782,6 @@ async def break_lease( 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")) @@ -4644,64 +4794,27 @@ async def break_lease( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def upload_range( # pylint: disable=too-many-locals + async def renew_lease( self, - optional_body: Optional[bytes] = None, *, - range: str, - file_range_write: Union[str, _models.FileRangeWriteType], - content_length: int, + lease_id: str, 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, + sharesnapshot: Optional[str] = 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. + """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. - :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._generated.models.FileRangeWriteType - :keyword content_length: The number of bytes being transmitted in the request body. Required. - :paramtype content_length: int + :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 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._generated.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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4714,32 +4827,19 @@ async def upload_range( # pylint: disable=too-many-locals } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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 + action: Literal["renew"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "renew")) 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, + _request = build_share_renew_lease_request( lease_id=lease_id, - file_last_written_mode=file_last_written_mode, - allow_trailing_dot=allow_trailing_dot, + timeout=timeout, + sharesnapshot=sharesnapshot, file_request_intent=file_request_intent, - structured_body_type=structured_body_type, - structured_content_length=structured_content_length, - content_type=content_type, + action=action, version=self._config.version, - content=_content, headers=_headers, params=_params, ) @@ -4755,7 +4855,7 @@ async def upload_range( # pylint: disable=too-many-locals response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -4766,16 +4866,7 @@ async def upload_range( # pylint: disable=too-many-locals 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-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( @@ -4787,71 +4878,37 @@ async def upload_range( # pylint: disable=too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def upload_range_from_url( # pylint: disable=too-many-locals + async def break_lease( 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[str] = None, - source_if_match_crc64: Optional[str] = None, - source_if_none_match_crc64: Optional[str] = None, + break_period: Optional[int] = 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, + sharesnapshot: Optional[str] = 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. + """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 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._generated.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: str - :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: str - :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: str + :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 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._generated.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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4867,24 +4924,16 @@ async def upload_range_from_url( # pylint: disable=too-many-locals _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_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, + _request = build_share_break_lease_request( 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, + break_period=break_period, 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, + sharesnapshot=sharesnapshot, file_request_intent=file_request_intent, + action=action, version=self._config.version, headers=_headers, params=_params, @@ -4901,7 +4950,7 @@ async def upload_range_from_url( # pylint: disable=too-many-locals response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -4912,13 +4961,8 @@ async def upload_range_from_url( # pylint: disable=too-many-locals 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("str", 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-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( @@ -4930,46 +4974,24 @@ async def upload_range_from_url( # pylint: disable=too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_range_list( + async def create_snapshot( 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, + metadata: Optional[dict[str, str]] = 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. + ) -> None: + """Creates a read-only snapshot of a share. - :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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4983,17 +5005,12 @@ async def get_range_list( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ShareFileRangeList] = kwargs.pop("cls", None) + cls: ClsType[None] = 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, + _request = build_share_create_snapshot_request( + timeout=timeout, + metadata=metadata, file_request_intent=file_request_intent, - support_rename=support_rename, version=self._config.version, headers=_headers, params=_params, @@ -5003,20 +5020,14 @@ async def get_range_list( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + 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, @@ -5025,121 +5036,120 @@ async def get_range_list( 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["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")) - 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 cls(pipeline_response, None, response_headers) # type: ignore - return deserialized # 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 start_copy( # pylint: disable=too-many-locals + async def create_permission( self, + permission: Union[_models.SharePermission, JSON, IO[bytes]], *, - 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. + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. - :keyword copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. - Required. - :paramtype copy_source: str + :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 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._generated.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._generated.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._generated.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._generated.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._generated.models.OwnerCopyMode + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5152,35 +5162,25 @@ async def start_copy( # pylint: disable=too-many-locals } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) 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) - _request = build_file_start_copy_request( - copy_source=copy_source, + 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, - 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, + content_type=content_type, version=self._config.version, + content=_content, headers=_headers, params=_params, ) @@ -5196,7 +5196,7 @@ async def start_copy( # pylint: disable=too-many-locals response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -5205,10 +5205,9 @@ async def start_copy( # pylint: disable=too-many-locals 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-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( @@ -5220,35 +5219,31 @@ async def start_copy( # pylint: disable=too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def abort_copy( + async def get_permission( self, *, - copyid: str, + file_permission_key: str, timeout: Optional[int] = None, - lease_id: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = 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. + ) -> _models.SharePermission: + """Returns the permission (security descriptor) for a given permission key. This is used to + support file level ACLs for SMB shares. - :keyword copyid: The copy identifier provided in the x-ms-copy-id header of the original Copy - File operation. Required. - :paramtype copyid: 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. Required. + :paramtype file_permission_key: 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_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._generated.models.ShareTokenIntent - :return: None - :rtype: 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 = { @@ -5262,18 +5257,13 @@ async def abort_copy( _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) + cls: ClsType[_models.SharePermission] = kwargs.pop("cls", None) - _request = build_file_abort_copy_request( - copyid=copyid, + _request = build_share_get_permission_request( + file_permission_key=file_permission_key, timeout=timeout, - lease_id=lease_id, - allow_trailing_dot=allow_trailing_dot, + file_permission_format=file_permission_format, file_request_intent=file_request_intent, - copy_action_abort_constant=copy_action_abort_constant, version=self._config.version, headers=_headers, params=_params, @@ -5283,14 +5273,20 @@ async def abort_copy( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + 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, @@ -5305,42 +5301,79 @@ async def abort_copy( "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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def list_handles( + async def set_properties( # pylint: disable=too-many-locals self, *, - marker: Optional[str] = None, - maxresults: Optional[int] = None, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - allow_trailing_dot: Optional[bool] = 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 - ) -> _models.ListHandlesResponse: - """Lists handles for file. + ) -> None: + """Sets properties for the specified share. - :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 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._generated.models.ShareTokenIntent - :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse + :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 = { @@ -5354,15 +5387,22 @@ async def list_handles( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_list_handles_request( - marker=marker, - maxresults=maxresults, + _request = build_share_set_properties_request( timeout=timeout, - sharesnapshot=sharesnapshot, - allow_trailing_dot=allow_trailing_dot, + 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, @@ -5372,8 +5412,7 @@ async def list_handles( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -5381,11 +5420,6 @@ async def list_handles( 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, @@ -5394,55 +5428,61 @@ async def list_handles( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def force_close_handles( + async def set_metadata( self, *, - handle_id: str, timeout: Optional[int] = None, - marker: Optional[str] = None, - sharesnapshot: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any ) -> None: - """Closes all handles open for given file. + """Sets one or more user-defined name-value pairs for the specified share. - :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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5460,12 +5500,10 @@ async def force_close_handles( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_force_close_handles_request( - handle_id=handle_id, + _request = build_share_set_metadata_request( timeout=timeout, - marker=marker, - sharesnapshot=sharesnapshot, - allow_trailing_dot=allow_trailing_dot, + metadata=metadata, + lease_id=lease_id, file_request_intent=file_request_intent, version=self._config.version, headers=_headers, @@ -5492,13 +5530,8 @@ async def force_close_handles( 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["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( @@ -5510,82 +5543,26 @@ async def force_close_handles( 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 + 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 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._generated.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 + :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._generated.models.ShareTokenIntent - :return: None - :rtype: 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 = { @@ -5599,26 +5576,11 @@ async def rename( # pylint: disable=too-many-locals _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) - _request = build_file_rename_request( - rename_source=rename_source, + _request = build_share_get_access_policy_request( 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, + lease_id=lease_id, file_request_intent=file_request_intent, version=self._config.version, headers=_headers, @@ -5629,7 +5591,8 @@ async def rename( # pylint: disable=too-many-locals } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 ) @@ -5637,6 +5600,11 @@ async def rename( # pylint: disable=too-many-locals 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, @@ -5647,75 +5615,45 @@ async def rename( # pylint: disable=too-many-locals 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def create_symbolic_link( + async def set_access_policy( self, + share_acl: Optional[_models.SignedIdentifiers] = None, *, - 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. + """Sets stored access policies for the share that may be used with Shared Access Signatures. - :keyword link_text: NFS only. The path to the original file, the symbolic link is pointing to. - Required. - :paramtype link_text: str + :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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5728,22 +5666,25 @@ async def create_symbolic_link( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) 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) - _request = build_file_create_symbolic_link_request( - link_text=link_text, + if share_acl is not None: + _content = _get_element(share_acl) + else: + _content = None + + _request = build_share_set_access_policy_request( 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, + content_type=content_type, version=self._config.version, + content=_content, headers=_headers, params=_params, ) @@ -5759,7 +5700,7 @@ async def create_symbolic_link( response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -5770,21 +5711,6 @@ async def create_symbolic_link( 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( @@ -5796,26 +5722,25 @@ async def create_symbolic_link( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def get_symbolic_link( + async def get_statistics( self, *, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, + lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any - ) -> None: - """Returns the target of a symbolic link. NFS only. + ) -> _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 sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a - share snapshot. Default value is None. - :paramtype sharesnapshot: 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._generated.models.ShareTokenIntent - :return: None - :rtype: 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 = { @@ -5829,11 +5754,11 @@ async def get_symbolic_link( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ShareStats] = kwargs.pop("cls", None) - _request = build_file_get_symbolic_link_request( + _request = build_share_get_statistics_request( timeout=timeout, - sharesnapshot=sharesnapshot, + lease_id=lease_id, file_request_intent=file_request_intent, version=self._config.version, headers=_headers, @@ -5844,7 +5769,8 @@ async def get_symbolic_link( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 ) @@ -5852,6 +5778,11 @@ async def get_symbolic_link( 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, @@ -5862,40 +5793,46 @@ async def get_symbolic_link( 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async - async def create_hard_link( + async def restore( self, *, - target_file: str, timeout: Optional[int] = None, - lease_id: 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 ) -> None: - """Creates a hard link to a target file. NFS only. + """Restores a previously deleted share. - :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 + :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 lease_id: str + :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5911,15 +5848,13 @@ async def create_hard_link( _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, + _request = build_share_restore_request( timeout=timeout, - lease_id=lease_id, + deleted_share_name=deleted_share_name, + deleted_share_version=deleted_share_version, file_request_intent=file_request_intent, - file_type=file_type, version=self._config.version, headers=_headers, params=_params, @@ -5947,22 +5882,19 @@ async def create_hard_link( 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-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-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-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-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") + 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-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( 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 index 3724e6c1b762..cc7dd0e7fd56 100644 --- 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 @@ -294,7 +294,7 @@ class Error(_Model): "TotalSharesProvisionedIopsExceedsAccountLimit", "TotalSharesProvisionedBandwidthExceedsAccountLimit", and "TotalSharesCountExceedsAccountLimit". - :vartype code: str or ~azure.storage.fileshare._generated.models.StorageErrorCode + :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. @@ -659,7 +659,7 @@ class HandleItem(_Model): :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._generated.models.AccessRight] + :vartype access_right_list: list[str or ~azure.storage.fileshare.models.AccessRight] """ handle_id: str = rest_field( @@ -1347,7 +1347,7 @@ class SharePermission(_Model): Required. :vartype permission: str :ivar format: The permission format. Known values are: "Sddl" and "Binary". - :vartype format: str or ~azure.storage.fileshare._generated.models.FilePermissionFormat + :vartype format: str or ~azure.storage.fileshare.models.FilePermissionFormat """ permission: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -1407,18 +1407,18 @@ class SharePropertiesInternal(_Model): :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._generated.models.LeaseStatusType + :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._generated.models.LeaseStateType + :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._generated.models.LeaseDurationType + :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._generated.models.ShareRootSquash + :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 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 51785ce60910..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 @@ -12,20 +12,20 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import ServiceOperations # type: ignore -from ._operations import ShareOperations # 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/_operations.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/operations/_operations.py index 9ebabdd0039d..b796310e7992 100644 --- 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 @@ -40,19 +40,31 @@ _SERIALIZER.client_side_validation = False -def build_service_set_properties_request( +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 {}) - 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" + _url = "?restype=directory" # Construct parameters if timeout is not None: @@ -60,29 +72,60 @@ def build_service_set_properties_request( # Construct headers _headers["x-ms-version"] = _SERIALIZER.header("version", version, "str") - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "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_service_get_properties_request( +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")) - accept = _headers.pop("Accept", "application/xml") - # Construct URL - _url = "/?restype=service&comp=properties" + _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") @@ -90,92 +133,106 @@ def build_service_get_properties_request( _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") + 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_service_list_shares_segment_request( # pylint: disable=name-too-long +def build_directory_delete_request( *, - 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, + 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")) - accept = _headers.pop("Accept", "application/xml") - # Construct URL - _url = "/?comp=list" + _url = "?restype=directory" # 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") + 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) + return HttpRequest(method="DELETE", 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 +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 {}) - 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" + _url = "?restype=directory&comp=properties" # 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") + 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="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_create_request( +def build_directory_set_metadata_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, + allow_trailing_dot: Optional[bool] = 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 {}) @@ -183,7 +240,7 @@ def build_share_create_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?restype=share" + _url = "?restype=directory&comp=metadata" # Construct parameters if timeout is not None: @@ -193,288 +250,419 @@ def build_share_create_request( _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 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 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( +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, - 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")) + accept = _headers.pop("Accept", "application/xml") + # Construct URL - _url = "?restype=share" + _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") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_delete_request( +def build_directory_list_handles_request( *, - sharesnapshot: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, timeout: Optional[int] = None, - delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = 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")) + accept = _headers.pop("Accept", "application/xml") + # Construct URL - _url = "?restype=share" + _url = "?comp=listhandles" # Construct parameters - 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 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 delete_snapshots is not None: - _headers["x-ms-delete-snapshots"] = _SERIALIZER.header("delete_snapshots", delete_snapshots, "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") - if lease_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_acquire_lease_request( +def build_directory_force_close_handles_request( # pylint: disable=name-too-long *, + handle_id: str, timeout: Optional[int] = None, - lease_duration: Optional[int] = None, - proposed_lease_id: Optional[str] = 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 {}) - 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" + _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") - 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") + _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_share_release_lease_request( +def build_directory_rename_request( *, - lease_id: str, + rename_source: str, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = 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 {}) - 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" + _url = "?restype=directory&comp=rename" # 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") + _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_share_change_lease_request( +def build_file_create_request( # pylint: disable=too-many-locals,too-many-statements,too-many-branches *, - lease_id: str, - proposed_lease_id: Optional[str] = None, + content_length: int, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = 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, + optional_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 {}) - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + 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 = "?restype=share&comp=lease" + _url = "" # 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 content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["x-ms-content-length"] = _SERIALIZER.header("content_length", 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 optional_content_length is not None: + _headers["Content-Length"] = _SERIALIZER.header("optional_content_length", optional_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_share_renew_lease_request( +def build_file_download_request( *, - lease_id: str, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = 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 {}) - 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")) + accept = _headers.pop("Accept", "application/octet-stream") + # Construct URL - _url = "?restype=share&comp=lease" + _url = "" # 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 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="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_break_lease_request( +def build_file_get_properties_request( *, + sharesnapshot: Optional[str] = None, timeout: Optional[int] = None, - break_period: Optional[int] = None, lease_id: 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 {}) - 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" + _url = "" # 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") + if timeout is not None: + _params["timeout"] = _SERIALIZER.query("timeout", timeout, "int") # 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 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) + return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_create_snapshot_request( +def build_file_delete_request( *, 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: @@ -483,7 +671,7 @@ def build_share_create_snapshot_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?restype=share&comp=snapshot" + _url = "" # Construct parameters if timeout is not None: @@ -491,58 +679,47 @@ def build_share_create_snapshot_request( # 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 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) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_create_permission_request( +def build_file_set_http_headers_request( # pylint: disable=too-many-locals *, 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_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")) - accept = _headers.pop("Accept", "application/json") - # Construct URL - _url = "?restype=share&comp=filepermission" + _url = "?comp=properties" # Construct parameters if timeout is not None: @@ -550,33 +727,61 @@ def build_share_get_permission_request( # 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_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") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_set_properties_request( +def build_file_set_metadata_request( *, timeout: Optional[int] = None, - quota: Optional[int] = None, - access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, + metadata: Optional[dict[str, str]] = 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -584,7 +789,7 @@ def build_share_set_properties_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?restype=share&comp=properties" + _url = "?comp=metadata" # Construct parameters if timeout is not None: @@ -592,62 +797,34 @@ def build_share_set_properties_request( # 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 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 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" - ) + 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_share_set_metadata_request( +def build_file_acquire_lease_request( *, timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = None, - lease_id: Optional[str] = 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 = "?restype=share&comp=metadata" + _url = "?comp=lease" # Construct parameters if timeout is not None: @@ -655,31 +832,34 @@ def build_share_set_metadata_request( # 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 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_share_get_access_policy_request( +def build_file_release_lease_request( *, + lease_id: str, 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["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) 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" + _url = "?comp=lease" # Construct parameters if timeout is not None: @@ -687,29 +867,32 @@ def build_share_get_access_policy_request( # 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-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") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_set_access_policy_request( +def build_file_change_lease_request( *, + lease_id: str, timeout: Optional[int] = None, - lease_id: Optional[str] = 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 {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + 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=acl" + _url = "?comp=lease" # Construct parameters if timeout is not None: @@ -717,31 +900,33 @@ def build_share_set_access_policy_request( # 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") + _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_share_get_statistics_request( +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")) - accept = _headers.pop("Accept", "application/xml") - # Construct URL - _url = "?restype=share&comp=stats" + _url = "?comp=lease" # Construct parameters if timeout is not None: @@ -751,27 +936,37 @@ def build_share_get_statistics_request( _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") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_share_restore_request( +def build_file_upload_range_request( *, + range: str, + file_range_write: Union[str, _models.FileRangeWriteType], + content_length: int, timeout: Optional[int] = None, - deleted_share_name: Optional[str] = None, - deleted_share_version: Optional[str] = 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 = "?restype=share&comp=undelete" + _url = "?comp=range" # Construct parameters if timeout is not None: @@ -779,35 +974,50 @@ def build_share_restore_request( # 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 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_directory_create_request( +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, - 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, + source_content_crc64: Optional[str] = None, + source_if_match_crc64: Optional[str] = None, + source_if_none_match_crc64: Optional[str] = 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 {}) @@ -815,7 +1025,7 @@ def build_directory_create_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?restype=directory" + _url = "?comp=range" # Construct parameters if timeout is not None: @@ -823,116 +1033,114 @@ def build_directory_create_request( # 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" + _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, "str") + 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, "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 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, "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") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_directory_get_properties_request( +def build_file_get_range_list_request( *, sharesnapshot: Optional[str] = None, + prevsharesnapshot: Optional[str] = None, timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = 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 = "?restype=directory" + _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 file_request_intent is not None: - _headers["x-ms-file-request-intent"] = _SERIALIZER.header("file_request_intent", file_request_intent, "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") - - 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") + 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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_directory_set_properties_request( +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, - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = 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 {}) @@ -940,7 +1148,7 @@ def build_directory_set_properties_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?restype=directory&comp=properties" + _url = "" # Construct parameters if timeout is not None: @@ -948,10 +1156,23 @@ def build_directory_set_properties_request( # 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: @@ -960,12 +1181,18 @@ def build_directory_set_properties_request( _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 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: @@ -974,14 +1201,19 @@ def build_directory_set_properties_request( _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_directory_set_metadata_request( +def build_file_abort_copy_request( *, + copyid: 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 @@ -989,18 +1221,23 @@ def build_directory_set_metadata_request( _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 = "?restype=directory&comp=metadata" + _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") - if metadata is not None: - _headers["x-ms-meta"] = _SERIALIZER.header("metadata", metadata, "{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: @@ -1009,15 +1246,12 @@ def build_directory_set_metadata_request( 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 +def build_file_list_handles_request( *, - 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, + sharesnapshot: Optional[str] = None, allow_trailing_dot: Optional[bool] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any @@ -1029,26 +1263,20 @@ def build_directory_list_files_and_directories_segment_request( # pylint: disab accept = _headers.pop("Accept", "application/xml") # Construct URL - _url = "?restype=directory&comp=list" + _url = "?comp=listhandles" # 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") + if sharesnapshot is not None: + _params["sharesnapshot"] = _SERIALIZER.query("sharesnapshot", sharesnapshot, "str") # 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: @@ -1058,13 +1286,12 @@ def build_directory_list_files_and_directories_segment_request( # pylint: disab return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_directory_list_handles_request( +def build_file_force_close_handles_request( *, - marker: Optional[str] = None, - maxresults: Optional[int] = None, + 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 @@ -1073,76 +1300,31 @@ def build_directory_list_handles_request( _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" + _url = "?comp=forceclosehandles" # 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 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") - if recursive is not None: - _headers["x-ms-recursive"] = _SERIALIZER.header("recursive", recursive, "bool") + _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") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_directory_force_close_handles_request( # pylint: disable=name-too-long +def build_file_rename_request( *, - 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, + rename_source: str, timeout: Optional[int] = None, replace_if_exists: Optional[bool] = None, ignore_read_only: Optional[bool] = None, @@ -1156,6 +1338,7 @@ def build_directory_rename_request( 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, @@ -1166,7 +1349,7 @@ def build_directory_rename_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?restype=directory&comp=rename" + _url = "?comp=rename" # Construct parameters if timeout is not None: @@ -1203,6 +1386,8 @@ def build_directory_rename_request( _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: @@ -1215,46 +1400,25 @@ def build_directory_rename_request( 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 +def build_file_create_symbolic_link_request( *, - content_length: int, + link_text: 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: 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, - optional_content_length: Optional[int] = None, - structured_body_type: Optional[str] = None, - structured_content_length: 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 {}) - 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 = "" + _url = "?restype=symboliclink" # Construct parameters if timeout is not None: @@ -1262,167 +1426,98 @@ def build_file_create_request( # pylint: disable=too-many-locals,too-many-state # 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("content_length", 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 optional_content_length is not None: - _headers["Content-Length"] = _SERIALIZER.header("optional_content_length", optional_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" - ) + _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_download_request( +def build_file_get_symbolic_link_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, + sharesnapshot: Optional[str] = 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/xml") - # Construct URL - _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 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( +def build_file_create_hard_link_request( *, - sharesnapshot: Optional[str] = None, + target_file: 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 {}) + 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 = "" + _url = "?restype=hardlink" # 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") + _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") - 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-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="HEAD", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_delete_request( +def build_service_set_properties_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 {}) + content_type: str = kwargs.pop("content_type") version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "" + _url = "/?restype=service&comp=properties" # Construct parameters if timeout is not None: @@ -1430,47 +1525,27 @@ def build_file_delete_request( # 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") + _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_set_http_headers_request( # pylint: disable=too-many-locals +def build_service_get_properties_request( *, 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")) + accept = _headers.pop("Accept", "application/xml") + # Construct URL - _url = "?comp=properties" + _url = "/?restype=service&comp=properties" # Construct parameters if timeout is not None: @@ -1478,61 +1553,94 @@ def build_file_set_http_headers_request( # pylint: disable=too-many-locals # 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") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_set_metadata_request( +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, - lease_id: Optional[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, - allow_trailing_dot: Optional[bool] = 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 {}) @@ -1540,7 +1648,7 @@ def build_file_set_metadata_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?comp=metadata" + _url = "?restype=share" # Construct parameters if timeout is not None: @@ -1550,23 +1658,120 @@ def build_file_set_metadata_request( _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 allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + if lease_id is not None: + _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "str") - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_acquire_lease_request( +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, - allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1575,11 +1780,13 @@ def build_file_acquire_lease_request( 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" + _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") @@ -1590,18 +1797,16 @@ def build_file_acquire_lease_request( _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( +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, - allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1610,11 +1815,13 @@ def build_file_release_lease_request( 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" + _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") @@ -1622,19 +1829,17 @@ def build_file_release_lease_request( _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( +def build_share_change_lease_request( *, lease_id: str, - timeout: Optional[int] = None, proposed_lease_id: Optional[str] = None, + timeout: Optional[int] = None, + sharesnapshot: 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 {}) @@ -1643,11 +1848,13 @@ def build_file_change_lease_request( 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" + _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") @@ -1657,117 +1864,82 @@ def build_file_change_lease_request( _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( +def build_share_renew_lease_request( *, + lease_id: str, timeout: Optional[int] = None, - lease_id: Optional[str] = None, + sharesnapshot: 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")) + 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 = "?comp=lease" + _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_id is not None: - _headers["x-ms-lease-id"] = _SERIALIZER.header("lease_id", lease_id, "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_upload_range_request( +def build_share_break_lease_request( *, - range: str, - file_range_write: Union[str, _models.FileRangeWriteType], - content_length: int, timeout: Optional[int] = None, - content_md5: Optional[bytes] = None, + break_period: Optional[int] = None, lease_id: Optional[str] = None, - file_last_written_mode: Optional[Union[str, _models.FileLastWrittenMode]] = None, - allow_trailing_dot: Optional[bool] = None, + sharesnapshot: Optional[str] = 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)) + 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=range" + _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 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 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") - 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") + _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 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( +def build_share_create_snapshot_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[str] = None, - source_if_match_crc64: Optional[str] = None, - source_if_none_match_crc64: Optional[str] = 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, + metadata: Optional[dict[str, str]] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any ) -> HttpRequest: @@ -1776,7 +1948,7 @@ def build_file_upload_range_from_url_request( version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?comp=range" + _url = "?restype=share&comp=snapshot" # Construct parameters if timeout is not None: @@ -1784,122 +1956,58 @@ def build_file_upload_range_from_url_request( # 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, "str") - 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, "str" - ) - 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, "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 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_file_get_range_list_request( +def build_share_create_permission_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 {}) + 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")) - accept = _headers.pop("Accept", "application/xml") - # Construct URL - _url = "?comp=rangelist" + _url = "?restype=share&comp=filepermission" # 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 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") - 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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_start_copy_request( # pylint: disable=too-many-locals +def build_share_get_permission_request( *, - copy_source: str, + file_permission_key: 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")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = "" + _url = "?restype=share&comp=filepermission" # Construct parameters if timeout is not None: @@ -1907,103 +2015,95 @@ def build_file_start_copy_request( # pylint: disable=too-many-locals # 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") + _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_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) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_abort_copy_request( +def build_share_set_properties_request( *, - copyid: str, timeout: Optional[int] = None, + quota: Optional[int] = None, + access_tier: Optional[Union[str, _models.ShareAccessTier]] = None, lease_id: Optional[str] = None, - allow_trailing_dot: Optional[bool] = 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 {}) - 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" + _url = "?restype=share&comp=properties" # 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 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 allow_trailing_dot is not None: - _headers["x-ms-allow-trailing-dot"] = _SERIALIZER.header("allow_trailing_dot", allow_trailing_dot, "bool") + 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_file_list_handles_request( +def build_share_set_metadata_request( *, - marker: Optional[str] = None, - maxresults: Optional[int] = None, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any ) -> HttpRequest: @@ -2011,39 +2111,29 @@ def build_file_list_handles_request( _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" + _url = "?restype=share&comp=metadata" # 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 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") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_force_close_handles_request( +def build_share_get_access_policy_request( *, - handle_id: str, timeout: Optional[int] = None, - marker: Optional[str] = None, - sharesnapshot: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, + lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any ) -> HttpRequest: @@ -2051,56 +2141,10 @@ def build_file_force_close_handles_request( _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 {}) + accept = _headers.pop("Accept", "application/xml") - version: str = kwargs.pop("version", _headers.pop("x-ms-version", "2026-06-06")) # Construct URL - _url = "?comp=rename" + _url = "?restype=share&comp=acl" # Construct parameters if timeout is not None: @@ -2108,68 +2152,29 @@ def build_file_rename_request( # 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 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) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_file_create_symbolic_link_request( +def build_share_set_access_policy_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 {}) + 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=symboliclink" + _url = "?restype=share&comp=acl" # Construct parameters if timeout is not None: @@ -2177,29 +2182,20 @@ def build_file_create_symbolic_link_request( # 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 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 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( +def build_share_get_statistics_request( *, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, + lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any ) -> HttpRequest: @@ -2207,38 +2203,40 @@ def build_file_get_symbolic_link_request( _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=symboliclink" + _url = "?restype=share&comp=stats" # 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_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_file_create_hard_link_request( +def build_share_restore_request( *, - target_file: str, timeout: Optional[int] = None, - lease_id: 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 {}) - 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" + _url = "?restype=share&comp=undelete" # Construct parameters if timeout is not None: @@ -2246,24 +2244,26 @@ def build_file_create_hard_link_request( # 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 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 ServiceOperations: +class DirectoryOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare._generated.FileClient`'s - :attr:`service` attribute. + :class:`~azure.storage.fileshare.FileClient`'s + :attr:`directory` attribute. """ def __init__(self, *args, **kwargs) -> None: @@ -2274,25 +2274,75 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def set_properties( # pylint: disable=inconsistent-return-statements + def create( # pylint: disable=inconsistent-return-statements,too-many-locals self, - storage_service_properties: _models.StorageServiceProperties, *, 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: - """Sets properties for a storage account's File service endpoint, including properties for Storage - Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. + """Creates a new directory under the specified share or parent directory. - :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 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._generated.models.ShareTokenIntent + :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: @@ -2305,20 +2355,28 @@ def set_properties( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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( + _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, - content_type=content_type, + owner=owner, + group=group, + file_mode=file_mode, + file_property_semantics=file_property_semantics, + allow_trailing_dot=allow_trailing_dot, version=self._config.version, - content=_content, headers=_headers, params=_params, ) @@ -2334,7 +2392,7 @@ def set_properties( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -2343,35 +2401,67 @@ def set_properties( # pylint: disable=inconsistent-return-statements 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["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["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( + 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 - ) -> _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. + ) -> 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._generated.models.ShareTokenIntent - :return: StorageServiceProperties. The StorageServiceProperties is compatible with - MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.StorageServiceProperties + :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 = { @@ -2385,11 +2475,13 @@ def get_properties( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.StorageServiceProperties] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_service_get_properties_request( + _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, @@ -2399,8 +2491,7 @@ def get_properties( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2408,11 +2499,6 @@ def get_properties( 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, @@ -2421,58 +2507,64 @@ def get_properties( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def list_shares_segment( + def delete( # pylint: disable=inconsistent-return-statements 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any - ) -> _models.ListSharesResponse: - """The List Shares Segment operation returns a list of the shares and share snapshots under the - specified account. + ) -> None: + """Removes the specified empty directory. Note that the directory must be empty before it can be + deleted. - :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._generated.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._generated.models.ListSharesIncludeType] - :return: ListSharesResponse. The ListSharesResponse is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ListSharesResponse + :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 = { @@ -2486,15 +2578,12 @@ def list_shares_segment( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListSharesResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_service_list_shares_segment_request( - prefix=prefix, - marker=marker, - maxresults=maxresults, + _request = build_directory_delete_request( timeout=timeout, file_request_intent=file_request_intent, - include=include, + allow_trailing_dot=allow_trailing_dot, version=self._config.version, headers=_headers, params=_params, @@ -2504,20 +2593,14 @@ def list_shares_segment( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + 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, @@ -2532,31 +2615,74 @@ def list_shares_segment( "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 + return cls(pipeline_response, None, response_headers) # 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. + 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. - :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 + :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 = { @@ -2567,19 +2693,26 @@ def get_user_delegation_key( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_service_get_user_delegation_key_request( + _request = build_directory_set_properties_request( timeout=timeout, - content_type=content_type, + 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, - content=_content, headers=_headers, params=_params, ) @@ -2588,8 +2721,7 @@ def get_user_delegation_key( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2597,11 +2729,6 @@ def get_user_delegation_key( 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, @@ -2610,105 +2737,62 @@ def get_user_delegation_key( 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")) - 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._generated.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") + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def create( # pylint: disable=inconsistent-return-statements,too-many-locals + def set_metadata( # pylint: disable=inconsistent-return-statements 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, + allow_trailing_dot: Optional[bool] = 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. + """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 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._generated.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._generated.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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -2726,21 +2810,11 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_create_request( + _request = build_directory_set_metadata_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, + allow_trailing_dot=allow_trailing_dot, 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, @@ -2757,7 +2831,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -2767,19 +2841,8 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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-request-server-encrypted"] = self._deserialize( + "bool", response.headers.get("x-ms-request-server-encrypted") ) 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")) @@ -2792,31 +2855,49 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def get_properties( # pylint: disable=inconsistent-return-statements + 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, - lease_id: Optional[str] = None, **kwargs: Any - ) -> None: - """Returns all user-defined metadata and system properties for the specified share or share - snapshot. + ) -> _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._generated.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 + :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 = { @@ -2830,13 +2911,18 @@ def get_properties( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ListFilesAndDirectoriesSegmentResponse] = kwargs.pop("cls", None) - _request = build_share_get_properties_request( + _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, - lease_id=lease_id, version=self._config.version, headers=_headers, params=_params, @@ -2846,7 +2932,8 @@ def get_properties( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 ) @@ -2854,6 +2941,11 @@ def get_properties( # pylint: disable=inconsistent-return-statements 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, @@ -2862,107 +2954,59 @@ def get_properties( # pylint: disable=inconsistent-return-statements 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( - "str", 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements + def list_handles( self, *, - sharesnapshot: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = None, timeout: Optional[int] = None, - delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, + sharesnapshot: Optional[str] = None, + recursive: Optional[bool] = None, + allow_trailing_dot: Optional[bool] = 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. + ) -> _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 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._generated.models.DeleteSnapshotsOptionType + :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._generated.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 + :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 = { @@ -2976,14 +3020,16 @@ def delete( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) - _request = build_share_delete_request( - sharesnapshot=sharesnapshot, + _request = build_directory_list_handles_request( + marker=marker, + maxresults=maxresults, timeout=timeout, - delete_snapshots=delete_snapshots, + sharesnapshot=sharesnapshot, + recursive=recursive, + allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, - lease_id=lease_id, version=self._config.version, headers=_headers, params=_params, @@ -2993,14 +3039,20 @@ def delete( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [202]: + 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, @@ -3009,52 +3061,58 @@ def delete( # pylint: disable=inconsistent-return-statements 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def acquire_lease( # pylint: disable=inconsistent-return-statements + def force_close_handles( # pylint: disable=inconsistent-return-statements self, *, + handle_id: str, timeout: Optional[int] = None, - lease_duration: Optional[int] = None, - proposed_lease_id: Optional[str] = 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: - """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. + """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 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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3070,16 +3128,16 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements _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( + _request = build_directory_force_close_handles_request( + handle_id=handle_id, timeout=timeout, - lease_duration=lease_duration, - proposed_lease_id=proposed_lease_id, + marker=marker, sharesnapshot=sharesnapshot, + recursive=recursive, + allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, - action=action, version=self._config.version, headers=_headers, params=_params, @@ -3096,7 +3154,7 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -3105,9 +3163,13 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements 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-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( @@ -3119,28 +3181,75 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def release_lease( # pylint: disable=inconsistent-return-statements + def rename( # pylint: disable=inconsistent-return-statements,too-many-locals self, *, - lease_id: str, + rename_source: str, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = 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: - """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. + """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 lease_id: Specifies the current lease ID on the resource. Required. - :paramtype lease_id: str + :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 sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a - share snapshot. Default value is None. - :paramtype sharesnapshot: str + :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3156,15 +3265,26 @@ def release_lease( # pylint: disable=inconsistent-return-statements _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, + _request = build_directory_rename_request( + rename_source=rename_source, timeout=timeout, - sharesnapshot=sharesnapshot, + 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, - action=action, version=self._config.version, headers=_headers, params=_params, @@ -3192,6 +3312,26 @@ def release_lease( # pylint: disable=inconsistent-return-statements 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( @@ -3202,34 +3342,152 @@ def release_lease( # pylint: disable=inconsistent-return-statements 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, + +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, + *, + 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, + optional_content_length: Optional[int] = None, + structured_body_type: Optional[str] = None, + structured_content_length: Optional[int] = 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. + """Creates a new file or replaces a file. Note it only initializes the file with no content. - :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 + :param optional_body: Initial data. Default value is None. + :type optional_body: bytes + :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. + Required. + :paramtype content_length: 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 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._generated.models.ShareTokenIntent + :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 optional_content_length: Optional. Specifies the content length of the file. Default + value is None. + :paramtype optional_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: @@ -3242,20 +3500,51 @@ def change_lease( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + 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) - _request = build_share_change_lease_request( - lease_id=lease_id, - proposed_lease_id=proposed_lease_id, + _content = optional_body + + _request = build_file_create_request( + content_length=content_length, timeout=timeout, - sharesnapshot=sharesnapshot, + 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, - action=action, + owner=owner, + group=group, + file_mode=file_mode, + nfs_file_type=nfs_file_type, + content_md5=content_md5, + file_property_semantics=file_property_semantics, + optional_content_length=optional_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, ) @@ -3271,7 +3560,7 @@ def change_lease( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -3282,7 +3571,35 @@ def change_lease( # pylint: disable=inconsistent-return-statements 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-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( @@ -3294,30 +3611,42 @@ def change_lease( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def renew_lease( # pylint: disable=inconsistent-return-statements + def download( self, *, - lease_id: str, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = 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 - ) -> 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. + ) -> Iterator[bytes]: + """Reads or downloads a file from the system, including its metadata and properties. - :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 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._generated.models.ShareTokenIntent - :return: None - :rtype: 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 = { @@ -3331,15 +3660,16 @@ def renew_lease( # pylint: disable=inconsistent-return-statements _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) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _request = build_share_renew_lease_request( - lease_id=lease_id, + _request = build_file_download_request( timeout=timeout, - sharesnapshot=sharesnapshot, + 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, - action=action, + structured_body_type=structured_body_type, version=self._config.version, headers=_headers, params=_params, @@ -3349,14 +3679,20 @@ def renew_lease( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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]: + 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, @@ -3365,54 +3701,106 @@ def renew_lease( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["Last-Modified"] = self._deserialize("str", 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["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["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( + "str", 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-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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def break_lease( # pylint: disable=inconsistent-return-statements + def get_properties( self, *, + sharesnapshot: Optional[str] = None, timeout: Optional[int] = None, - break_period: Optional[int] = None, lease_id: 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: - """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. + ) -> 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 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 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._generated.models.ShareTokenIntent - :return: None - :rtype: None + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: bool + :rtype: bool :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3426,16 +3814,14 @@ def break_lease( # pylint: disable=inconsistent-return-statements _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( + _request = build_file_get_properties_request( + sharesnapshot=sharesnapshot, timeout=timeout, - break_period=break_period, lease_id=lease_id, - sharesnapshot=sharesnapshot, + allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, - action=action, version=self._config.version, headers=_headers, params=_params, @@ -3452,7 +3838,7 @@ def break_lease( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -3461,10 +3847,55 @@ def break_lease( # pylint: disable=inconsistent-return-statements raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["Last-Modified"] = self._deserialize("str", 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["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["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( + "str", 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( @@ -3474,25 +3905,30 @@ def break_lease( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore + return 200 <= response.status_code <= 299 @distributed_trace - def create_snapshot( # pylint: disable=inconsistent-return-statements + def delete( # pylint: disable=inconsistent-return-statements self, *, 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 ) -> None: - """Creates a read-only snapshot of a share. + """Removes the file from the storage account. :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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -3510,9 +3946,10 @@ def create_snapshot( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_create_snapshot_request( + _request = build_file_delete_request( timeout=timeout, - metadata=metadata, + lease_id=lease_id, + allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, version=self._config.version, headers=_headers, @@ -3530,7 +3967,7 @@ def create_snapshot( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -3539,9 +3976,7 @@ def create_snapshot( # pylint: disable=inconsistent-return-statements 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-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( @@ -3552,111 +3987,100 @@ def create_snapshot( # pylint: disable=inconsistent-return-statements 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._generated.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._generated.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._generated.models.ShareTokenIntent - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace - def create_permission( # pylint: disable=inconsistent-return-statements + def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many-locals self, - permission: Union[_models.SharePermission, JSON, IO[bytes]], *, 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: - """Create a permission (a security descriptor). This is used to support file level ACLs for SMB - shares. + """Sets HTTP headers on a file. - :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_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._generated.models.ShareTokenIntent + :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: @@ -3669,25 +4093,34 @@ def create_permission( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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( + _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, - content_type=content_type, + owner=owner, + group=group, + file_mode=file_mode, version=self._config.version, - content=_content, headers=_headers, params=_params, ) @@ -3703,7 +4136,7 @@ def create_permission( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -3712,9 +4145,32 @@ def create_permission( # pylint: disable=inconsistent-return-statements 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( @@ -3726,33 +4182,32 @@ def create_permission( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def get_permission( + def set_metadata( # pylint: disable=inconsistent-return-statements self, *, - file_permission_key: str, timeout: Optional[int] = None, - file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = 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 - ) -> _models.SharePermission: - """Returns the permission (security descriptor) for a given permission key. This is used to - support file level ACLs for SMB shares. + ) -> None: + """Sets one or more user-defined name-value pairs for the specified file. - :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 + :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 file_permission_format: str or - ~azure.storage.fileshare._generated.models.FilePermissionFormat + :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._generated.models.ShareTokenIntent - :return: SharePermission. The SharePermission is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.SharePermission + :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 = { @@ -3766,13 +4221,14 @@ def get_permission( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.SharePermission] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_get_permission_request( - file_permission_key=file_permission_key, + _request = build_file_set_metadata_request( timeout=timeout, - file_permission_format=file_permission_format, + 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, @@ -3782,8 +4238,7 @@ def get_permission( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3791,11 +4246,6 @@ def get_permission( 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, @@ -3804,84 +4254,49 @@ def get_permission( 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["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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def set_properties( # pylint: disable=inconsistent-return-statements,too-many-locals + def acquire_lease( # pylint: disable=inconsistent-return-statements 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, + lease_duration: Optional[int] = None, + proposed_lease_id: Optional[str] = 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> None: - """Sets properties for the specified share. + """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 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._generated.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._generated.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 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._generated.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 + :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: @@ -3897,22 +4312,16 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l _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_set_properties_request( + _request = build_file_acquire_lease_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, + lease_duration=lease_duration, + proposed_lease_id=proposed_lease_id, 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, + allow_trailing_dot=allow_trailing_dot, + action=action, version=self._config.version, headers=_headers, params=_params, @@ -3929,7 +4338,7 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -3940,28 +4349,7 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l 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-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( @@ -3973,27 +4361,27 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def set_metadata( # pylint: disable=inconsistent-return-statements + def release_lease( # pylint: disable=inconsistent-return-statements self, *, + lease_id: 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> None: - """Sets one or more user-defined name-value pairs for the specified share. + """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 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._generated.models.ShareTokenIntent + :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: @@ -4009,13 +4397,15 @@ def set_metadata( # pylint: disable=inconsistent-return-statements _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_set_metadata_request( - timeout=timeout, - metadata=metadata, + _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, @@ -4054,27 +4444,34 @@ def set_metadata( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def get_access_policy( + def change_lease( # pylint: disable=inconsistent-return-statements self, *, + lease_id: str, timeout: Optional[int] = None, - lease_id: Optional[str] = None, + proposed_lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any - ) -> _models.SignedIdentifiers: - """Returns information about stored access policies specified on the share that may be used with - Shared Access Signatures. + ) -> 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 lease_id: If specified, the lease ID must match the lease ID of the file. Default - value is None. - :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 file_request_intent: Valid values are 'backup'. "backup" Default value is None. - :paramtype file_request_intent: str or - ~azure.storage.fileshare._generated.models.ShareTokenIntent - :return: SignedIdentifiers. The SignedIdentifiers is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.SignedIdentifiers + :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 = { @@ -4088,12 +4485,16 @@ def get_access_policy( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_get_access_policy_request( - timeout=timeout, + _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, @@ -4103,8 +4504,7 @@ def get_access_policy( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -4112,11 +4512,6 @@ def get_access_policy( 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, @@ -4127,46 +4522,40 @@ def get_access_policy( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def set_access_policy( # pylint: disable=inconsistent-return-statements + def break_lease( # 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, + allow_trailing_dot: Optional[bool] = None, **kwargs: Any ) -> None: - """Sets stored access policies for the share that may be used with Shared Access Signatures. + """The Lease File operation establishes and manages a lock on a file for write and delete + operations. - :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._generated.models.ShareTokenIntent + :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: @@ -4179,25 +4568,19 @@ def set_access_policy( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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 + action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) 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( + _request = build_file_break_lease_request( timeout=timeout, lease_id=lease_id, file_request_intent=file_request_intent, - content_type=content_type, + allow_trailing_dot=allow_trailing_dot, + action=action, version=self._config.version, - content=_content, headers=_headers, params=_params, ) @@ -4213,7 +4596,7 @@ def set_access_policy( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -4224,6 +4607,8 @@ def set_access_policy( # pylint: disable=inconsistent-return-statements 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( @@ -4235,26 +4620,63 @@ def set_access_policy( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def get_statistics( + 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 - ) -> _models.ShareStats: - """Retrieves statistics related to the share. + ) -> 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._generated.models.ShareTokenIntent - :return: ShareStats. The ShareStats is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ShareStats + :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 = { @@ -4265,16 +4687,32 @@ def get_statistics( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ShareStats] = kwargs.pop("cls", None) + 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) - _request = build_share_get_statistics_request( + _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, ) @@ -4283,20 +4721,14 @@ def get_statistics( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + 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, @@ -4307,47 +4739,90 @@ def get_statistics( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def restore( # pylint: disable=inconsistent-return-statements + 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, - deleted_share_name: Optional[str] = None, - deleted_share_version: Optional[str] = None, + source_content_crc64: Optional[str] = None, + source_if_match_crc64: Optional[str] = None, + source_if_none_match_crc64: Optional[str] = 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: - """Restores a previously deleted share. + """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 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 + :keyword source_content_crc64: Specify the CRC64 hash of the source content. Default value is + None. + :paramtype source_content_crc64: str + :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: str + :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: str + :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default value is None. - :paramtype deleted_share_version: str + :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4365,10 +4840,21 @@ def restore( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_share_restore_request( + _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, - deleted_share_name=deleted_share_name, - deleted_share_version=deleted_share_version, + 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, @@ -4397,18 +4883,12 @@ def restore( # pylint: disable=inconsistent-return-statements 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-content-crc64"] = self._deserialize("str", 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-share-max-burst-credits-for-iops"] = self._deserialize( - "int", response.headers.get("x-ms-share-max-burst-credits-for-iops") + 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")) @@ -4420,98 +4900,46 @@ def restore( # pylint: disable=inconsistent-return-statements if cls: return cls(pipeline_response, None, response_headers) # type: ignore - -class DirectoryOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.storage.fileshare._generated.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 + def get_range_list( 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 + *, + 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 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._generated.models.FilePermissionFormat - :keyword file_request_intent: Valid values are 'backup'. "backup" Default value is None. - :paramtype file_request_intent: str or - ~azure.storage.fileshare._generated.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._generated.models.FilePropertySemantics + :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 - :return: None - :rtype: None + :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 = { @@ -4525,24 +4953,17 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ShareFileRangeList] = kwargs.pop("cls", None) - _request = build_directory_create_request( + _request = build_file_get_range_list_request( + sharesnapshot=sharesnapshot, + prevsharesnapshot=prevsharesnapshot, 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, + 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, @@ -4552,14 +4973,20 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [201]: + 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, @@ -4568,66 +4995,118 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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["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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def get_properties( # pylint: disable=inconsistent-return-statements + def start_copy( # pylint: disable=inconsistent-return-statements,too-many-locals self, *, - sharesnapshot: Optional[str] = None, + copy_source: str, timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = 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: - """Returns all system properties for the specified directory, and can also be used to check the - existence of a directory. + """Copies a blob or file to a destination file within the storage account. - :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a - share snapshot. Default value is None. - :paramtype sharesnapshot: 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 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._generated.models.ShareTokenIntent + :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: @@ -4645,11 +5124,29 @@ def get_properties( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_get_properties_request( - sharesnapshot=sharesnapshot, + _request = build_file_start_copy_request( + copy_source=copy_source, timeout=timeout, - file_request_intent=file_request_intent, + 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, @@ -4666,42 +5163,19 @@ def get_properties( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [200]: + 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-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 = {} + 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( @@ -4713,25 +5187,32 @@ def get_properties( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def delete( # pylint: disable=inconsistent-return-statements + def abort_copy( # pylint: disable=inconsistent-return-statements self, *, + copyid: str, timeout: Optional[int] = None, - file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = 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 specified empty directory. Note that the directory must be empty before it can be - deleted. + """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 file_request_intent: Valid values are 'backup'. "backup" Default value is None. - :paramtype file_request_intent: str or - ~azure.storage.fileshare._generated.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 :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: @@ -4747,12 +5228,18 @@ def delete( # pylint: disable=inconsistent-return-statements _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_directory_delete_request( + _request = build_file_abort_copy_request( + copyid=copyid, timeout=timeout, - file_request_intent=file_request_intent, + 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, @@ -4769,7 +5256,7 @@ def delete( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -4789,71 +5276,36 @@ def delete( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def set_properties( # pylint: disable=inconsistent-return-statements,too-many-locals + def list_handles( self, *, + marker: Optional[str] = None, + maxresults: Optional[int] = None, 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, + sharesnapshot: 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 properties for the specified directory. + ) -> _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 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._generated.models.FilePermissionFormat + :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._generated.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 + :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 = { @@ -4867,22 +5319,15 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) - _request = build_directory_set_properties_request( + _request = build_file_list_handles_request( + marker=marker, + maxresults=maxresults, 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, + sharesnapshot=sharesnapshot, 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, @@ -4892,7 +5337,8 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 ) @@ -4900,6 +5346,11 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l 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, @@ -4908,63 +5359,54 @@ def set_properties( # pylint: disable=inconsistent-return-statements,too-many-l 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def set_metadata( # pylint: disable=inconsistent-return-statements + def force_close_handles( # pylint: disable=inconsistent-return-statements self, *, + handle_id: str, timeout: Optional[int] = None, - metadata: Optional[dict[str, str]] = 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: - """Sets one or more user-defined name-value pairs for the specified directory. + """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 metadata: Optional. User-defined metadata for the resource. Default value is None. - :paramtype metadata: dict[str, 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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4982,9 +5424,11 @@ def set_metadata( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_set_metadata_request( + _request = build_file_force_close_handles_request( + handle_id=handle_id, timeout=timeout, - metadata=metadata, + marker=marker, + sharesnapshot=sharesnapshot, allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, version=self._config.version, @@ -5012,9 +5456,12 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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["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")) @@ -5027,51 +5474,80 @@ def set_metadata( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def list_files_and_directories_segment( + def rename( # pylint: disable=inconsistent-return-statements,too-many-locals 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, + rename_source: str, timeout: Optional[int] = None, - include_extended_info: Optional[bool] = 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 - ) -> _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. + ) -> 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 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._generated.models.ListFilesIncludeType] + :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 include_extended_info: Include extended information. Default value is None. - :paramtype include_extended_info: bool + :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._generated.models.ShareTokenIntent - :return: ListFilesAndDirectoriesSegmentResponse. The ListFilesAndDirectoriesSegmentResponse is - compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ListFilesAndDirectoriesSegmentResponse + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5085,17 +5561,26 @@ def list_files_and_directories_segment( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListFilesAndDirectoriesSegmentResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_list_files_and_directories_segment_request( - prefix=prefix, - sharesnapshot=sharesnapshot, - marker=marker, - maxresults=maxresults, - include=include, + _request = build_file_rename_request( + rename_source=rename_source, timeout=timeout, - include_extended_info=include_extended_info, + 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, @@ -5106,8 +5591,7 @@ def list_files_and_directories_segment( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -5115,11 +5599,6 @@ def list_files_and_directories_segment( 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, @@ -5128,60 +5607,78 @@ def list_files_and_directories_segment( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def list_handles( + def create_symbolic_link( # pylint: disable=inconsistent-return-statements self, *, - marker: Optional[str] = None, - maxresults: Optional[int] = None, + link_text: str, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - recursive: Optional[bool] = None, - allow_trailing_dot: Optional[bool] = 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 - ) -> _models.ListHandlesResponse: - """Lists handles for directory. + ) -> None: + """Creates a symbolic link to a target file. NFS only. - :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 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 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 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._generated.models.ShareTokenIntent - :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5195,15 +5692,17 @@ def list_handles( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_list_handles_request( - marker=marker, - maxresults=maxresults, + _request = build_file_create_symbolic_link_request( + link_text=link_text, timeout=timeout, - sharesnapshot=sharesnapshot, - recursive=recursive, - allow_trailing_dot=allow_trailing_dot, + 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, @@ -5214,20 +5713,14 @@ def list_handles( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + 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, @@ -5236,59 +5729,51 @@ def list_handles( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def force_close_handles( # pylint: disable=inconsistent-return-statements + def get_symbolic_link( # 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. + """Returns the target of a symbolic link. NFS only. - :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5306,13 +5791,9 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_directory_force_close_handles_request( - handle_id=handle_id, + _request = build_file_get_symbolic_link_request( 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, @@ -5339,95 +5820,41 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements 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["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 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, + + 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: - """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. + """Creates a hard link to a target file. NFS only. - :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 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 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 + :keyword lease_id: If specified, the lease ID must match the lease ID of 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._generated.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 + :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5443,26 +5870,15 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals _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_directory_rename_request( - rename_source=rename_source, + _request = build_file_create_hard_link_request( + target_file=target_file, 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, + lease_id=lease_id, file_request_intent=file_request_intent, + file_type=file_type, version=self._config.version, headers=_headers, params=_params, @@ -5479,7 +5895,7 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -5490,15 +5906,6 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals 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") ) @@ -5510,6 +5917,11 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals ) 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( @@ -5521,14 +5933,14 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore -class FileOperations: # pylint: disable=too-many-public-methods +class ServiceOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through - :class:`~azure.storage.fileshare._generated.FileClient`'s - :attr:`file` attribute. + :class:`~azure.storage.fileshare.FileClient`'s + :attr:`service` attribute. """ def __init__(self, *args, **kwargs) -> None: @@ -5539,135 +5951,24 @@ def __init__(self, *args, **kwargs) -> None: 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 + def set_properties( # pylint: disable=inconsistent-return-statements self, - optional_body: Optional[bytes] = None, + storage_service_properties: _models.StorageServiceProperties, *, - 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, - optional_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. + """Sets properties for a storage account's File service endpoint, including properties for Storage + Analytics metrics and CORS (Cross-Origin Resource Sharing) rules. - :param optional_body: Initial data. Default value is None. - :type optional_body: bytes - :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. - Required. - :paramtype content_length: int + :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_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._generated.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._generated.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._generated.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._generated.models.FilePropertySemantics - :keyword optional_content_length: Optional. Specifies the content length of the file. Default - value is None. - :paramtype optional_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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -5683,45 +5984,14 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals _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 + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) cls: ClsType[None] = kwargs.pop("cls", None) - _content = optional_body + _content = _get_element(storage_service_properties) - _request = build_file_create_request( - content_length=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, - optional_content_length=optional_content_length, - structured_body_type=structured_body_type, - structured_content_length=structured_content_length, - file_type=file_type, + _request = build_service_set_properties_request( + timeout=timeout, + file_request_intent=file_request_intent, content_type=content_type, version=self._config.version, content=_content, @@ -5740,7 +6010,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -5749,37 +6019,6 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals 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( @@ -5791,43 +6030,23 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def download( + def get_properties( 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. + ) -> _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 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._generated.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] + :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 = { @@ -5841,16 +6060,11 @@ def download( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + cls: ClsType[_models.StorageServiceProperties] = kwargs.pop("cls", None) - _request = build_file_download_request( + _request = build_service_get_properties_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, @@ -5861,14 +6075,14 @@ def download( _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", 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, 206]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -5882,62 +6096,6 @@ def download( raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["Last-Modified"] = self._deserialize("str", 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( - "str", 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-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( @@ -5946,7 +6104,10 @@ def download( 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 _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 @@ -5954,35 +6115,37 @@ def download( return deserialized # type: ignore @distributed_trace - def get_properties( + def list_shares_segment( self, *, - sharesnapshot: Optional[str] = None, + prefix: Optional[str] = None, + marker: Optional[str] = None, + maxresults: Optional[int] = 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, + include: Optional[list[Union[str, _models.ListSharesIncludeType]]] = None, **kwargs: Any - ) -> bool: - """Returns all user-defined metadata, standard HTTP properties, and system properties for the - file. + ) -> _models.ListSharesResponse: + """The List Shares Segment operation returns a list of the shares and share snapshots under the + specified account. - :keyword sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a - share snapshot. Default value is None. - :paramtype sharesnapshot: str + :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 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._generated.models.ShareTokenIntent - :return: bool - :rtype: bool + :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 = { @@ -5996,14 +6159,15 @@ def get_properties( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ListSharesResponse] = kwargs.pop("cls", None) - _request = build_file_get_properties_request( - sharesnapshot=sharesnapshot, + _request = build_service_list_shares_segment_request( + prefix=prefix, + marker=marker, + maxresults=maxresults, timeout=timeout, - lease_id=lease_id, - allow_trailing_dot=allow_trailing_dot, file_request_intent=file_request_intent, + include=include, version=self._config.version, headers=_headers, params=_params, @@ -6013,107 +6177,59 @@ def get_properties( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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]: - 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("str", 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( - "str", 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 = 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, None, response_headers) # type: ignore - return 200 <= response.status_code <= 299 + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @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. + 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 - :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._generated.models.ShareTokenIntent - :return: None - :rtype: None + :return: UserDelegationKey. The UserDelegationKey is compatible with MutableMapping + :rtype: ~azure.storage.fileshare._generated.models.UserDelegationKey :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6124,17 +6240,19 @@ def delete( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/xml")) + cls: ClsType[_models.UserDelegationKey] = kwargs.pop("cls", None) - _request = build_file_delete_request( + _content = _get_element(key_info) + + _request = build_service_get_user_delegation_key_request( timeout=timeout, - lease_id=lease_id, - allow_trailing_dot=allow_trailing_dot, - file_request_intent=file_request_intent, + content_type=content_type, version=self._config.version, + content=_content, headers=_headers, params=_params, ) @@ -6143,14 +6261,20 @@ def delete( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [202]: + 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, @@ -6159,113 +6283,104 @@ def delete( # pylint: disable=inconsistent-return-statements 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")) + 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, None, response_headers) # type: ignore + 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 set_http_headers( # pylint: disable=inconsistent-return-statements,too-many-locals + def create( # 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, + 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, - owner: Optional[str] = None, - group: Optional[str] = None, - file_mode: Optional[str] = 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 HTTP headers on a file. + """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 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 + :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 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 + :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 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._generated.models.FilePermissionFormat - :keyword lease_id: If specified, the lease ID must match the lease ID of the file. Default + :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 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._generated.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 + :paramtype enable_smb_directory_lease: bool :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6283,28 +6398,21 @@ def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_set_http_headers_request( + _request = build_share_create_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, + 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, - owner=owner, - group=group, - file_mode=file_mode, + 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, @@ -6321,7 +6429,7 @@ def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -6332,30 +6440,19 @@ def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many 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-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-file-creation-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-creation-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-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-time") + response_headers["x-ms-share-included-burst-iops"] = self._deserialize( + "int", response.headers.get("x-ms-share-included-burst-iops") ) - response_headers["x-ms-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") + 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-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( @@ -6367,31 +6464,28 @@ def set_http_headers( # pylint: disable=inconsistent-return-statements,too-many return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def set_metadata( # pylint: disable=inconsistent-return-statements + def get_properties( # pylint: disable=inconsistent-return-statements self, *, + sharesnapshot: Optional[str] = None, 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, + lease_id: Optional[str] = None, **kwargs: Any ) -> None: - """Sets one or more user-defined name-value pairs for the specified file. + """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 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 :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._generated.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: @@ -6409,12 +6503,11 @@ def set_metadata( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_set_metadata_request( + _request = build_share_get_properties_request( + sharesnapshot=sharesnapshot, timeout=timeout, - metadata=metadata, - lease_id=lease_id, file_request_intent=file_request_intent, - allow_trailing_dot=allow_trailing_dot, + lease_id=lease_id, version=self._config.version, headers=_headers, params=_params, @@ -6440,9 +6533,65 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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["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-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( + "str", 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")) @@ -6455,35 +6604,32 @@ def set_metadata( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def acquire_lease( # pylint: disable=inconsistent-return-statements + def delete( # pylint: disable=inconsistent-return-statements self, *, + sharesnapshot: Optional[str] = None, timeout: Optional[int] = None, - lease_duration: Optional[int] = None, - proposed_lease_id: Optional[str] = None, + delete_snapshots: Optional[Union[str, _models.DeleteSnapshotsOptionType]] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, - allow_trailing_dot: Optional[bool] = None, + lease_id: Optional[str] = None, **kwargs: Any ) -> None: - """The Lease File operation establishes and manages a lock on a file for write and delete - operations. + """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 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 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._generated.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 + :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: @@ -6499,16 +6645,14 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements _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( + _request = build_share_delete_request( + sharesnapshot=sharesnapshot, timeout=timeout, - lease_duration=lease_duration, - proposed_lease_id=proposed_lease_id, + delete_snapshots=delete_snapshots, file_request_intent=file_request_intent, - allow_trailing_dot=allow_trailing_dot, - action=action, + lease_id=lease_id, version=self._config.version, headers=_headers, params=_params, @@ -6525,7 +6669,7 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -6534,9 +6678,12 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements 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-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( @@ -6548,28 +6695,34 @@ def acquire_lease( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def release_lease( # pylint: disable=inconsistent-return-statements + def acquire_lease( # pylint: disable=inconsistent-return-statements self, *, - lease_id: str, 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, - 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. + """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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6585,14 +6738,15 @@ def release_lease( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) + action: Literal["acquire"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "acquire")) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_release_lease_request( - lease_id=lease_id, + _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, - allow_trailing_dot=allow_trailing_dot, action=action, version=self._config.version, headers=_headers, @@ -6610,7 +6764,7 @@ def release_lease( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [200]: + 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, @@ -6621,6 +6775,7 @@ def release_lease( # pylint: disable=inconsistent-return-statements 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( @@ -6632,33 +6787,27 @@ def release_lease( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def change_lease( # pylint: disable=inconsistent-return-statements + def release_lease( # pylint: disable=inconsistent-return-statements self, *, lease_id: str, timeout: Optional[int] = None, - proposed_lease_id: Optional[str] = None, + sharesnapshot: 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. + """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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6674,15 +6823,14 @@ def change_lease( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) + action: Literal["release"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "release")) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_change_lease_request( + _request = build_share_release_lease_request( lease_id=lease_id, timeout=timeout, - proposed_lease_id=proposed_lease_id, + sharesnapshot=sharesnapshot, file_request_intent=file_request_intent, - allow_trailing_dot=allow_trailing_dot, action=action, version=self._config.version, headers=_headers, @@ -6711,7 +6859,6 @@ def change_lease( # pylint: disable=inconsistent-return-statements 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( @@ -6723,29 +6870,32 @@ def change_lease( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def break_lease( # pylint: disable=inconsistent-return-statements + def change_lease( # pylint: disable=inconsistent-return-statements self, *, + lease_id: str, + proposed_lease_id: Optional[str] = None, timeout: Optional[int] = None, - lease_id: Optional[str] = None, + sharesnapshot: 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. + """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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6761,14 +6911,15 @@ def break_lease( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - action: Literal["break"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "break")) + action: Literal["change"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "change")) cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_break_lease_request( - timeout=timeout, + _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, - allow_trailing_dot=allow_trailing_dot, action=action, version=self._config.version, headers=_headers, @@ -6786,7 +6937,7 @@ def break_lease( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -6797,7 +6948,6 @@ def break_lease( # pylint: disable=inconsistent-return-statements 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")) @@ -6810,64 +6960,27 @@ def break_lease( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def upload_range( # pylint: disable=inconsistent-return-statements,too-many-locals + def renew_lease( # pylint: disable=inconsistent-return-statements self, - optional_body: Optional[bytes] = None, *, - range: str, - file_range_write: Union[str, _models.FileRangeWriteType], - content_length: int, + lease_id: str, 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, + sharesnapshot: Optional[str] = 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. + """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. - :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._generated.models.FileRangeWriteType - :keyword content_length: The number of bytes being transmitted in the request body. Required. - :paramtype content_length: int + :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 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._generated.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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -6880,32 +6993,19 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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 + action: Literal["renew"] = kwargs.pop("action", _headers.pop("x-ms-lease-action", "renew")) 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, + _request = build_share_renew_lease_request( lease_id=lease_id, - file_last_written_mode=file_last_written_mode, - allow_trailing_dot=allow_trailing_dot, + timeout=timeout, + sharesnapshot=sharesnapshot, file_request_intent=file_request_intent, - structured_body_type=structured_body_type, - structured_content_length=structured_content_length, - content_type=content_type, + action=action, version=self._config.version, - content=_content, headers=_headers, params=_params, ) @@ -6921,7 +7021,7 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -6932,16 +7032,7 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc 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-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( @@ -6953,71 +7044,37 @@ def upload_range( # pylint: disable=inconsistent-return-statements,too-many-loc return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too-many-locals + def break_lease( # pylint: disable=inconsistent-return-statements 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[str] = None, - source_if_match_crc64: Optional[str] = None, - source_if_none_match_crc64: Optional[str] = None, + break_period: Optional[int] = 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, + sharesnapshot: Optional[str] = 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. + """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 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._generated.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: str - :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: str - :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: str + :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 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._generated.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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7033,24 +7090,16 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too _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_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, + _request = build_share_break_lease_request( 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, + break_period=break_period, 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, + sharesnapshot=sharesnapshot, file_request_intent=file_request_intent, + action=action, version=self._config.version, headers=_headers, params=_params, @@ -7067,7 +7116,7 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -7078,13 +7127,8 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too 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("str", 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-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( @@ -7096,46 +7140,24 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def get_range_list( + def create_snapshot( # pylint: disable=inconsistent-return-statements 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, + metadata: Optional[dict[str, str]] = 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. + ) -> None: + """Creates a read-only snapshot of a share. - :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 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._generated.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 + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7149,17 +7171,12 @@ def get_range_list( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ShareFileRangeList] = kwargs.pop("cls", None) + cls: ClsType[None] = 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, + _request = build_share_create_snapshot_request( + timeout=timeout, + metadata=metadata, file_request_intent=file_request_intent, - support_rename=support_rename, version=self._config.version, headers=_headers, params=_params, @@ -7169,20 +7186,14 @@ def get_range_list( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + 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, @@ -7191,121 +7202,120 @@ def get_range_list( 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["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")) - 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 cls(pipeline_response, None, response_headers) # type: ignore - return deserialized # 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 start_copy( # pylint: disable=inconsistent-return-statements,too-many-locals + def create_permission( # pylint: disable=inconsistent-return-statements self, + permission: Union[_models.SharePermission, JSON, IO[bytes]], *, - 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. + """Create a permission (a security descriptor). This is used to support file level ACLs for SMB + shares. - :keyword copy_source: Specifies the URL of the source file or blob, up to 2 KB in length. - Required. - :paramtype copy_source: str + :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 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._generated.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._generated.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._generated.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._generated.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._generated.models.OwnerCopyMode + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7318,35 +7328,25 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) 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) - _request = build_file_start_copy_request( - copy_source=copy_source, + 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, - 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, + content_type=content_type, version=self._config.version, + content=_content, headers=_headers, params=_params, ) @@ -7362,7 +7362,7 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local response = pipeline_response.http_response - if response.status_code not in [202]: + 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, @@ -7371,10 +7371,9 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local 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-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( @@ -7386,35 +7385,31 @@ def start_copy( # pylint: disable=inconsistent-return-statements,too-many-local return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def abort_copy( # pylint: disable=inconsistent-return-statements + def get_permission( self, *, - copyid: str, + file_permission_key: str, timeout: Optional[int] = None, - lease_id: Optional[str] = None, - allow_trailing_dot: Optional[bool] = None, + file_permission_format: Optional[Union[str, _models.FilePermissionFormat]] = 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. + ) -> _models.SharePermission: + """Returns the permission (security descriptor) for a given permission key. This is used to + support file level ACLs for SMB shares. - :keyword copyid: The copy identifier provided in the x-ms-copy-id header of the original Copy - File operation. Required. - :paramtype copyid: 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. Required. + :paramtype file_permission_key: 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_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._generated.models.ShareTokenIntent - :return: None - :rtype: 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 = { @@ -7428,18 +7423,13 @@ def abort_copy( # pylint: disable=inconsistent-return-statements _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) + cls: ClsType[_models.SharePermission] = kwargs.pop("cls", None) - _request = build_file_abort_copy_request( - copyid=copyid, + _request = build_share_get_permission_request( + file_permission_key=file_permission_key, timeout=timeout, - lease_id=lease_id, - allow_trailing_dot=allow_trailing_dot, + file_permission_format=file_permission_format, file_request_intent=file_request_intent, - copy_action_abort_constant=copy_action_abort_constant, version=self._config.version, headers=_headers, params=_params, @@ -7449,14 +7439,20 @@ def abort_copy( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + 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, @@ -7471,42 +7467,79 @@ def abort_copy( # pylint: disable=inconsistent-return-statements "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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def list_handles( + def set_properties( # pylint: disable=inconsistent-return-statements,too-many-locals self, *, - marker: Optional[str] = None, - maxresults: Optional[int] = None, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, - allow_trailing_dot: Optional[bool] = 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 - ) -> _models.ListHandlesResponse: - """Lists handles for file. + ) -> None: + """Sets properties for the specified share. - :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 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._generated.models.ShareTokenIntent - :return: ListHandlesResponse. The ListHandlesResponse is compatible with MutableMapping - :rtype: ~azure.storage.fileshare._generated.models.ListHandlesResponse + :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 = { @@ -7520,15 +7553,22 @@ def list_handles( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ListHandlesResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_list_handles_request( - marker=marker, - maxresults=maxresults, + _request = build_share_set_properties_request( timeout=timeout, - sharesnapshot=sharesnapshot, - allow_trailing_dot=allow_trailing_dot, + 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, @@ -7538,8 +7578,7 @@ def list_handles( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -7547,11 +7586,6 @@ def list_handles( 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, @@ -7560,55 +7594,61 @@ def list_handles( 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")) - 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 + return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def force_close_handles( # pylint: disable=inconsistent-return-statements + def set_metadata( # 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, + metadata: Optional[dict[str, str]] = None, + lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any ) -> None: - """Closes all handles open for given file. + """Sets one or more user-defined name-value pairs for the specified share. - :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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7626,12 +7666,10 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_file_force_close_handles_request( - handle_id=handle_id, + _request = build_share_set_metadata_request( timeout=timeout, - marker=marker, - sharesnapshot=sharesnapshot, - allow_trailing_dot=allow_trailing_dot, + metadata=metadata, + lease_id=lease_id, file_request_intent=file_request_intent, version=self._config.version, headers=_headers, @@ -7658,13 +7696,8 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements 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["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( @@ -7676,82 +7709,26 @@ def force_close_handles( # pylint: disable=inconsistent-return-statements 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 + 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 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._generated.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 + :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._generated.models.ShareTokenIntent - :return: None - :rtype: 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 = { @@ -7765,26 +7742,11 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.SignedIdentifiers] = kwargs.pop("cls", None) - _request = build_file_rename_request( - rename_source=rename_source, + _request = build_share_get_access_policy_request( 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, + lease_id=lease_id, file_request_intent=file_request_intent, version=self._config.version, headers=_headers, @@ -7795,7 +7757,8 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 ) @@ -7803,6 +7766,11 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals 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, @@ -7813,75 +7781,45 @@ def rename( # pylint: disable=inconsistent-return-statements,too-many-locals 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def create_symbolic_link( # pylint: disable=inconsistent-return-statements + def set_access_policy( # pylint: disable=inconsistent-return-statements self, + share_acl: Optional[_models.SignedIdentifiers] = None, *, - 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. + """Sets stored access policies for the share that may be used with Shared Access Signatures. - :keyword link_text: NFS only. The path to the original file, the symbolic link is pointing to. - Required. - :paramtype link_text: str + :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 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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -7894,22 +7832,25 @@ def create_symbolic_link( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) 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) - _request = build_file_create_symbolic_link_request( - link_text=link_text, + if share_acl is not None: + _content = _get_element(share_acl) + else: + _content = None + + _request = build_share_set_access_policy_request( 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, + content_type=content_type, version=self._config.version, + content=_content, headers=_headers, params=_params, ) @@ -7925,7 +7866,7 @@ def create_symbolic_link( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response - if response.status_code not in [201]: + 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, @@ -7936,21 +7877,6 @@ def create_symbolic_link( # pylint: disable=inconsistent-return-statements 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( @@ -7962,26 +7888,25 @@ def create_symbolic_link( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def get_symbolic_link( # pylint: disable=inconsistent-return-statements + def get_statistics( self, *, timeout: Optional[int] = None, - sharesnapshot: Optional[str] = None, + lease_id: Optional[str] = None, file_request_intent: Optional[Union[str, _models.ShareTokenIntent]] = None, **kwargs: Any - ) -> None: - """Returns the target of a symbolic link. NFS only. + ) -> _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 sharesnapshot: The snapshot parameter is an opaque DateTime value that specifies a - share snapshot. Default value is None. - :paramtype sharesnapshot: 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._generated.models.ShareTokenIntent - :return: None - :rtype: 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 = { @@ -7995,11 +7920,11 @@ def get_symbolic_link( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.ShareStats] = kwargs.pop("cls", None) - _request = build_file_get_symbolic_link_request( + _request = build_share_get_statistics_request( timeout=timeout, - sharesnapshot=sharesnapshot, + lease_id=lease_id, file_request_intent=file_request_intent, version=self._config.version, headers=_headers, @@ -8010,7 +7935,8 @@ def get_symbolic_link( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 ) @@ -8018,6 +7944,11 @@ def get_symbolic_link( # pylint: disable=inconsistent-return-statements 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, @@ -8028,40 +7959,46 @@ def get_symbolic_link( # pylint: disable=inconsistent-return-statements 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")) + 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, None, response_headers) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def create_hard_link( # pylint: disable=inconsistent-return-statements + def restore( # pylint: disable=inconsistent-return-statements self, *, - target_file: str, timeout: Optional[int] = None, - lease_id: 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 ) -> None: - """Creates a hard link to a target file. NFS only. + """Restores a previously deleted share. - :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 + :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 lease_id: str + :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._generated.models.ShareTokenIntent + :paramtype file_request_intent: str or ~azure.storage.fileshare.models.ShareTokenIntent :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -8077,15 +8014,13 @@ def create_hard_link( # pylint: disable=inconsistent-return-statements _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, + _request = build_share_restore_request( timeout=timeout, - lease_id=lease_id, + deleted_share_name=deleted_share_name, + deleted_share_version=deleted_share_version, file_request_intent=file_request_intent, - file_type=file_type, version=self._config.version, headers=_headers, params=_params, @@ -8113,22 +8048,19 @@ def create_hard_link( # pylint: disable=inconsistent-return-statements 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-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-file-last-write-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-last-write-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-file-change-time"] = self._deserialize( - "str", response.headers.get("x-ms-file-change-time") + 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-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( 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 d48b3af4a23e..06bd319c80b1 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( + generated.retention_policy + ), # pylint: disable=protected-access ) @@ -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]]: @@ -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: # pylint: disable=unused-argument + def __init__( + self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any + ) -> None: # pylint: disable=unused-argument self.encryption_in_transit = encryption_in_transit @@ -346,22 +348,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 +379,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 +443,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 +464,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 +517,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 +526,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 +606,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 +661,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 +674,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 +707,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 +731,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 +742,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 +785,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 +835,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 +852,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 +893,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 +903,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 +915,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 +954,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 +998,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 +1079,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,7 +1103,8 @@ 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) @@ -1091,8 +1113,12 @@ 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) 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 return self._response.next_marker or None, self.current_page @@ -1143,14 +1169,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,45 +1252,54 @@ 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] - last_modified = kwargs.get('Last-Modified') + 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] + last_modified = kwargs.get("Last-Modified") if isinstance(last_modified, str): last_modified = Deserializer.deserialize_rfc(last_modified) self.last_modified = 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.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): @@ -1285,6 +1320,7 @@ def _from_generated(cls, generated): class ShareProtocols(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Enabled protocols on the share""" + SMB = "SMB" NFS = "NFS" @@ -1314,20 +1350,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 @@ -1345,10 +1378,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) @@ -1357,8 +1390,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 a6705a794995..6e92e0bd54c9 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 @@ -11,8 +11,7 @@ _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" + "Size of file_permission is too large. file_permission should be <=8KB, else " "please use file_permission_key" ) 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 895bb81d8173..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 @@ -16,36 +16,36 @@ _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", ] 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 cbbb05d28d8c..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 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 a1637f3976ca..1d271a20a66b 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: diff --git a/sdk/storage/azure-storage-file-share/tests/conftest.py b/sdk/storage/azure-storage-file-share/tests/conftest.py index ee82af3e16c1..2be8b15e6cf4 100644 --- a/sdk/storage/azure-storage-file-share/tests/conftest.py +++ b/sdk/storage/azure-storage-file-share/tests/conftest.py @@ -18,7 +18,7 @@ set_custom_default_matcher, add_remove_header_sanitizer, add_uri_regex_sanitizer, - test_proxy + test_proxy, ) 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 52757465e08d..419a42afb8be 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_directory.py +++ b/sdk/storage/azure-storage-file-share/tests/test_directory.py @@ -1525,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__": 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 bef3c75711a8..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 @@ -1626,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 b1e3c4e8cc25..a046a1d8f1f6 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file.py @@ -4191,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() @@ -4201,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() @@ -4211,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() @@ -4229,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 @@ -4237,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_async.py b/sdk/storage/azure-storage-file-share/tests/test_file_async.py index 1be694b7ecff..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 @@ -4325,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() @@ -4335,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() @@ -4345,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() @@ -4365,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 ac4e33d30b23..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 @@ -15,7 +15,7 @@ ShareDirectoryClient, ShareFileClient, ShareServiceClient, - VERSION + VERSION, ) from devtools_testutils import recorded_by_proxy @@ -237,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", @@ -268,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): @@ -283,7 +284,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 @@ -300,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 @@ -308,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 @@ -318,7 +319,7 @@ 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.keys(): service = service_type( @@ -327,7 +328,7 @@ def test_create_service_ipv6_custom_domain(self): share_name="foo", directory_path="bar", file_path="baz", - token_intent="backup" + token_intent="backup", ) assert service is not None assert service.scheme == "https" 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 cd0c695ae0c8..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 @@ -229,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", @@ -260,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): @@ -275,7 +276,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 @@ -292,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 @@ -300,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 @@ -319,7 +320,7 @@ def test_create_service_ipv6_custom_domain(self): share_name="foo", directory_path="bar", file_path="baz", - token_intent="backup" + token_intent="backup", ) assert service is not None assert service.scheme == "https" From f22102c1ac2eaac94ae3391960119681d4a6fa55 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 14 Apr 2026 14:58:45 -0700 Subject: [PATCH 26/45] Fix pylint errors in azure-storage-file-share Move pylint disable comments to the correct lines where violations occur (protected-access, unused-argument) and fix implicit string concatenation in _parser.py. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/storage/fileshare/_models.py | 24 +++++++++---------- .../azure/storage/fileshare/_parser.py | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) 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 06bd319c80b1..a5612fb48be4 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 @@ -116,9 +116,9 @@ def _from_generated(cls, generated): version=generated.version, enabled=generated.enabled, include_apis=generated.include_apis, - retention_policy=RetentionPolicy._from_generated( + retention_policy=RetentionPolicy._from_generated( # pylint: disable=protected-access generated.retention_policy - ), # pylint: disable=protected-access + ), ) @@ -277,8 +277,8 @@ class ShareNfsSettings(GeneratedShareNfsSettings): """Sets the encryption in transit settings.""" def __init__( - self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any - ) -> None: # pylint: disable=unused-argument + self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any # pylint: disable=unused-argument + ) -> None: self.encryption_in_transit = encryption_in_transit @@ -743,8 +743,8 @@ def _extract_data_cb(self, get_next_return): 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 + 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 @@ -860,8 +860,8 @@ def _get_next_cb(self, continuation_token): 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 + 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 @@ -1114,11 +1114,11 @@ def _extract_data_cb(self, get_next_return): 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 + 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 + [FileProperties._from_generated(i) for i in self._response.segment.file_items] # pylint: disable=protected-access + ) return self._response.next_marker or None, self.current_page 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 6e92e0bd54c9..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 @@ -11,7 +11,7 @@ _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" + "Size of file_permission is too large. file_permission should be <=8KB, else please use file_permission_key" ) From 9efa7e65d7c4ee1c8b20f28cd93873c3d1592ba4 Mon Sep 17 00:00:00 2001 From: l0lawrence Date: Thu, 16 Apr 2026 13:29:40 -0700 Subject: [PATCH 27/45] Fix model subclasses to call super().__init__ and remove models _patch hacks Refactor the 10 custom subclasses in azure/storage/fileshare/_models.py (RetentionPolicy, Metrics, CorsRule, SmbMultichannel, SmbEncryptionInTransit, ShareSmbSettings, NfsEncryptionInTransit, ShareNfsSettings, ShareProtocolSettings, AccessPolicy) so they no longer shadow the parent _RestField descriptors and properly delegate to super().__init__(**kwargs). With the subclasses fixed at the source, the runtime monkey-patches in _generated/models/_patch.py (_patched_getattr/setattr/getattribute/new) are no longer needed; revert that file to the empty stock template. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../fileshare/_generated/models/_patch.py | 99 +-------------- .../azure/storage/fileshare/_models.py | 117 +++++------------- 2 files changed, 33 insertions(+), 183 deletions(-) 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 3cb55fced6ec..f7dd32510333 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,103 +1,14 @@ -# 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. -# -------------------------------------------------------------------------- +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ from typing import List -from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField - - -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() - } - 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 - - -__all__: List[str] = [] +__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/_models.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_models.py index a5612fb48be4..b4ca190f3dfe 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 @@ -55,17 +55,10 @@ class RetentionPolicy(GeneratedRetentionPolicy): All data older than this value will be deleted. """ - enabled: bool = False - """Indicates whether a retention policy is enabled for the storage service.""" - days: Optional[int] = None - """Indicates the number of days that metrics or logging or soft-deleted data should be retained. - All data older than this value will be deleted.""" - def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: - self.enabled = enabled - self.days = days - if self.enabled and (self.days is None): + if enabled and days is None: raise ValueError("If policy is enabled, 'days' must be specified.") + super().__init__(enabled=enabled, days=days) @classmethod def _from_generated(cls, generated): @@ -93,20 +86,13 @@ class Metrics(GeneratedMetrics): Determines how long the associated data should persist. """ - version: str = "1.0" - """The version of Storage Analytics to configure.""" - enabled: bool = False - """Indicates whether metrics are enabled for the File service.""" - include_apis: bool - """Indicates whether metrics should generate summary statistics for called API operations.""" - retention_policy: RetentionPolicy = RetentionPolicy() - """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() + super().__init__( + version=kwargs.get("version", "1.0"), + enabled=kwargs.get("enabled", False), + include_apis=kwargs.get("include_apis"), + retention_policy=kwargs.get("retention_policy") or RetentionPolicy(), + ) @classmethod def _from_generated(cls, generated): @@ -152,27 +138,14 @@ class CorsRule(GeneratedCorsRule): preflight response. """ - allowed_origins: str - """The comma-delimited string representation of the list of origin domains - that will be allowed via CORS, or "*" to allow all domains.""" - allowed_methods: str - """The comma-delimited string representation of the list of HTTP methods - that are allowed to be executed by the origin.""" - allowed_headers: str - """The comma-delimited string representation of the list of headers - allowed to be a part of the cross-origin request.""" - exposed_headers: str - """The comma-delimited string representation of the list of response - headers to expose to CORS clients.""" - max_age_in_seconds: int - """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) + super().__init__( + allowed_origins=",".join(allowed_origins), + allowed_methods=",".join(allowed_methods), + allowed_headers=",".join(kwargs.get("allowed_headers", [])), + exposed_headers=",".join(kwargs.get("exposed_headers", [])), + max_age_in_seconds=kwargs.get("max_age_in_seconds", 0), + ) @staticmethod def _to_generated(rules: Optional[List["CorsRule"]]) -> Optional[List[GeneratedCorsRule]]: @@ -209,11 +182,8 @@ class SmbMultichannel(GeneratedSmbMultichannel): :keyword bool enabled: If SMB Multichannel is enabled. """ - enabled: bool - """If SMB Multichannel is enabled.""" - def __init__(self, *, enabled: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self.enabled = enabled + super().__init__(enabled=enabled) class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): @@ -222,11 +192,8 @@ class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): :keyword bool required: If encryption in transit is required. """ - required: bool - """If encryption in transit is enabled.""" - def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self.required = required + super().__init__(required=required) class ShareSmbSettings(GeneratedShareSmbSettings): @@ -236,22 +203,16 @@ class ShareSmbSettings(GeneratedShareSmbSettings): :keyword SmbEncryptionInTransit encryption_in_transit: Sets the encryption in transit settings. """ - multichannel: Optional[SmbMultichannel] - """Sets the multichannel settings.""" - encryption_in_transit: Optional[SmbEncryptionInTransit] - """Sets the encryption in transit settings.""" - def __init__( - self, # pylint: disable=unused-argument + self, *, multichannel: Optional[SmbMultichannel] = None, encryption_in_transit: Optional[SmbEncryptionInTransit] = None, - **kwargs: Any + **kwargs: Any, # pylint: disable=unused-argument ) -> None: - self.multichannel = multichannel - self.encryption_in_transit = encryption_in_transit - if self.multichannel is None and self.encryption_in_transit is None: + if multichannel is None and encryption_in_transit is None: raise ValueError("The value 'multichannel' or 'encryption_in_transit' must be specified.") + super().__init__(multichannel=multichannel, encryption_in_transit=encryption_in_transit) class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): @@ -260,11 +221,8 @@ class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): :keyword bool required: If encryption in transit is required. """ - required: bool - """If encryption in transit is enabled.""" - def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self.required = required + super().__init__(required=required) class ShareNfsSettings(GeneratedShareNfsSettings): @@ -273,13 +231,10 @@ class ShareNfsSettings(GeneratedShareNfsSettings): :keyword NfsEncryptionInTransit encryption_in_transit: Sets the encryption in transit settings. """ - encryption_in_transit: NfsEncryptionInTransit - """Sets the encryption in transit settings.""" - def __init__( self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any # pylint: disable=unused-argument ) -> None: - self.encryption_in_transit = encryption_in_transit + super().__init__(encryption_in_transit=encryption_in_transit) class ShareProtocolSettings(GeneratedShareProtocolSettings): @@ -291,22 +246,16 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): :keyword ShareNfsSettings nfs: Sets NFS settings. """ - smb: Optional[ShareSmbSettings] - """Sets the SMB settings.""" - nfs: Optional[ShareNfsSettings] - """Sets the NFS settings.""" - def __init__( - self, # pylint: disable=unused-argument + self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, - **kwargs: Any + **kwargs: Any, # pylint: disable=unused-argument ) -> None: - self.smb = smb - self.nfs = nfs - if self.smb is None and self.nfs is None: + if smb is None and nfs is None: raise ValueError("The value 'smb' or 'nfs' must be specified.") + super().__init__(smb=smb, nfs=nfs) @classmethod def _from_generated(cls, generated): @@ -434,23 +383,13 @@ class AccessPolicy(GenAccessPolicy): :type start: ~datetime.datetime or str """ - permission: Optional[Union[ShareSasPermissions, str]] # type: ignore [assignment] - """The permissions associated with the shared access signature. The user is restricted to - operations allowed by the permissions.""" - expiry: Optional[Union["datetime", str]] # type: ignore [assignment] - """The time at which the shared access signature becomes invalid.""" - start: Optional[Union["datetime", str]] # type: ignore [assignment] - """The time at which the shared access signature becomes valid.""" - def __init__( self, permission: Optional[Union[ShareSasPermissions, str]] = None, expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - self.start = start - self.expiry = expiry - self.permission = permission + super().__init__(start=start, expiry=expiry, permission=permission) class LeaseProperties(DictMixin): From a32ff8f632b4fbd2c2762319aed3432322375eb2 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 16 Apr 2026 14:14:23 -0700 Subject: [PATCH 28/45] regen --- .../_generated/aio/operations/_operations.py | 24 ++++++------ .../fileshare/_generated/models/_models.py | 18 ++++----- .../_generated/operations/_operations.py | 38 ++++++++++--------- .../azure/storage/fileshare/_models.py | 15 +++++--- 4 files changed, 51 insertions(+), 44 deletions(-) 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 index 102996e2c972..9e74248e6551 100644 --- 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 @@ -1535,7 +1535,7 @@ async def download( raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["Last-Modified"] = self._deserialize("str", response.headers.get("Last-Modified")) + 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")) @@ -1547,7 +1547,7 @@ async def download( 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( - "str", response.headers.get("x-ms-copy-completion-time") + "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") @@ -1681,7 +1681,7 @@ async def get_properties( raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["Last-Modified"] = self._deserialize("str", response.headers.get("Last-Modified")) + 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")) @@ -1693,7 +1693,7 @@ async def get_properties( 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( - "str", response.headers.get("x-ms-copy-completion-time") + "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") @@ -2603,9 +2603,9 @@ async def upload_range_from_url( # pylint: disable=too-many-locals content_length: int, source_range: Optional[str] = None, timeout: Optional[int] = None, - source_content_crc64: Optional[str] = None, - source_if_match_crc64: Optional[str] = None, - source_if_none_match_crc64: 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, @@ -2633,13 +2633,13 @@ async def upload_range_from_url( # pylint: disable=too-many-locals :paramtype timeout: int :keyword source_content_crc64: Specify the CRC64 hash of the source content. Default value is None. - :paramtype source_content_crc64: str + :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: str + :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: str + :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 @@ -2717,7 +2717,9 @@ async def upload_range_from_url( # pylint: disable=too-many-locals 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("str", response.headers.get("x-ms-content-crc64")) + 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") ) 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 index cc7dd0e7fd56..bbb76cf01ad1 100644 --- 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 @@ -471,8 +471,8 @@ class FileProperty(_Model): :vartype change_time: ~datetime.datetime :ivar last_modified: The last modified time. :vartype last_modified: ~datetime.datetime - :ivar e_tag: The ETag of the file. - :vartype e_tag: str + :ivar etag: The ETag of the file. + :vartype etag: str """ content_length: int = rest_field( @@ -519,8 +519,7 @@ class FileProperty(_Model): xml={"attribute": False, "name": "Last-Modified", "text": False, "unwrapped": False}, ) """The last modified time.""" - e_tag: Optional[str] = rest_field( - name="eTag", + etag: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Etag", "text": False, "unwrapped": False}, ) @@ -538,7 +537,7 @@ def __init__( last_write_time: Optional[datetime.datetime] = None, change_time: Optional[datetime.datetime] = None, last_modified: Optional[datetime.datetime] = None, - e_tag: Optional[str] = None, + etag: Optional[str] = None, ) -> None: ... @overload @@ -1381,8 +1380,8 @@ class SharePropertiesInternal(_Model): :ivar last_modified: The last modified time. Required. :vartype last_modified: ~datetime.datetime - :ivar e_tag: The ETag of the share. Required. - :vartype e_tag: str + :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. @@ -1449,8 +1448,7 @@ class SharePropertiesInternal(_Model): xml={"attribute": False, "name": "Last-Modified", "text": False, "unwrapped": False}, ) """The last modified time. Required.""" - e_tag: str = rest_field( - name="eTag", + etag: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Etag", "text": False, "unwrapped": False}, ) @@ -1624,7 +1622,7 @@ def __init__( # pylint: disable=too-many-locals self, *, last_modified: datetime.datetime, - e_tag: str, + etag: str, quota: int, provisioned_iops: Optional[int] = None, provisioned_ingress_m_bps: Optional[int] = None, 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 index b796310e7992..7ec09992d382 100644 --- 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 @@ -1009,9 +1009,9 @@ def build_file_upload_range_from_url_request( content_length: int, source_range: Optional[str] = None, timeout: Optional[int] = None, - source_content_crc64: Optional[str] = None, - source_if_match_crc64: Optional[str] = None, - source_if_none_match_crc64: 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, @@ -1040,14 +1040,16 @@ def build_file_upload_range_from_url_request( _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, "str") + _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, "str" + "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, "str" + "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") @@ -3701,7 +3703,7 @@ def download( raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["Last-Modified"] = self._deserialize("str", response.headers.get("Last-Modified")) + 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")) @@ -3713,7 +3715,7 @@ def download( 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( - "str", response.headers.get("x-ms-copy-completion-time") + "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") @@ -3847,7 +3849,7 @@ def get_properties( raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["Last-Modified"] = self._deserialize("str", response.headers.get("Last-Modified")) + 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")) @@ -3859,7 +3861,7 @@ def get_properties( 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( - "str", response.headers.get("x-ms-copy-completion-time") + "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") @@ -4769,9 +4771,9 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too content_length: int, source_range: Optional[str] = None, timeout: Optional[int] = None, - source_content_crc64: Optional[str] = None, - source_if_match_crc64: Optional[str] = None, - source_if_none_match_crc64: 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, @@ -4799,13 +4801,13 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too :paramtype timeout: int :keyword source_content_crc64: Specify the CRC64 hash of the source content. Default value is None. - :paramtype source_content_crc64: str + :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: str + :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: str + :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 @@ -4883,7 +4885,9 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too 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("str", response.headers.get("x-ms-content-crc64")) + 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") ) 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 b4ca190f3dfe..04858ed76416 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 @@ -463,7 +463,7 @@ def __init__( content_disposition: Optional[str] = None, cache_control: Optional[str] = None, content_md5: Optional[bytearray] = None, - **kwargs: Any + **kwargs: Any, ) -> None: self.content_type = content_type or kwargs.get("Content-Type") self.content_encoding = content_encoding or kwargs.get("Content-Encoding") @@ -585,7 +585,7 @@ def _from_generated(cls, generated): props = cls() props.name = generated.name props.last_modified = generated.properties.last_modified - props.etag = generated.properties.e_tag + props.etag = generated.properties.etag props.quota = generated.properties.quota props.access_tier = generated.properties.access_tier props.next_allowed_quota_downgrade_time = generated.properties.next_allowed_quota_downgrade_time @@ -983,7 +983,7 @@ def _from_generated(cls, generated): props.last_access_time = generated.properties.last_access_time props.last_write_time = generated.properties.last_write_time props.change_time = generated.properties.change_time - props.etag = generated.properties.e_tag + props.etag = generated.properties.etag props.permission_key = generated.permission_key return props @@ -1053,10 +1053,13 @@ def _extract_data_cb(self, get_next_return): 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 + 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 + [ + FileProperties._from_generated(i) for i in self._response.segment.file_items + ] # pylint: disable=protected-access ) return self._response.next_marker or None, self.current_page @@ -1245,7 +1248,7 @@ def _from_generated(cls, generated): props = cls() props.name = unquote(generated.name.content) if generated.name.encoded else generated.name.content props.file_id = generated.file_id - props.etag = generated.properties.e_tag + props.etag = generated.properties.etag props.file_attributes = generated.attributes props.last_modified = generated.properties.last_modified props.creation_time = generated.properties.creation_time From ed8a579d480e79e8b62d2cebe7aab665b0d861e3 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 16 Apr 2026 14:51:53 -0700 Subject: [PATCH 29/45] mypy/pylint fix --- .../azure/storage/fileshare/_models.py | 23 +++++++++++-------- 1 file changed, 14 insertions(+), 9 deletions(-) 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 04858ed76416..a5316bef7c81 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 @@ -203,12 +203,12 @@ class ShareSmbSettings(GeneratedShareSmbSettings): :keyword SmbEncryptionInTransit encryption_in_transit: Sets the encryption in transit settings. """ - def __init__( + def __init__( # pylint: disable=unused-argument self, *, multichannel: Optional[SmbMultichannel] = None, encryption_in_transit: Optional[SmbEncryptionInTransit] = None, - **kwargs: Any, # pylint: disable=unused-argument + **kwargs: Any, ) -> None: if multichannel is None and encryption_in_transit is None: raise ValueError("The value 'multichannel' or 'encryption_in_transit' must be specified.") @@ -246,12 +246,12 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): :keyword ShareNfsSettings nfs: Sets NFS settings. """ - def __init__( + def __init__( # pylint: disable=unused-argument self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, - **kwargs: Any, # pylint: disable=unused-argument + **kwargs: Any, ) -> None: if smb is None and nfs is None: raise ValueError("The value 'smb' or 'nfs' must be specified.") @@ -383,13 +383,17 @@ class AccessPolicy(GenAccessPolicy): :type start: ~datetime.datetime or str """ + start: Optional[Union["datetime", str]] # type: ignore[assignment] + expiry: Optional[Union["datetime", str]] # type: ignore[assignment] + permission: Optional[Union[ShareSasPermissions, str]] # type: ignore[assignment] + def __init__( self, permission: Optional[Union[ShareSasPermissions, str]] = None, expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - super().__init__(start=start, expiry=expiry, permission=permission) + super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore[arg-type] class LeaseProperties(DictMixin): @@ -1053,13 +1057,14 @@ def _extract_data_cb(self, get_next_return): 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 + DirectoryProperties._from_generated(i) # pylint: disable=protected-access + 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: disable=protected-access + 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 From d6ee7b84f80fa558dc67b1a316e301bd18336e4e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 22 Apr 2026 10:18:43 -0700 Subject: [PATCH 30/45] regen --- .../_generated/aio/operations/_operations.py | 26 +++++++------- .../fileshare/_generated/models/_models.py | 16 ++++----- .../_generated/operations/_operations.py | 36 ++++++++++--------- 3 files changed, 41 insertions(+), 37 deletions(-) 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 index 9e74248e6551..1ee96a47a469 100644 --- 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 @@ -678,6 +678,7 @@ async def set_metadata( 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( @@ -1199,7 +1200,7 @@ async def create( # pylint: disable=too-many-locals self, optional_body: Optional[bytes] = None, *, - content_length: int, + file_content_length: int, timeout: Optional[int] = None, file_content_type: Optional[str] = None, file_content_encoding: Optional[str] = None, @@ -1224,7 +1225,7 @@ async def create( # pylint: disable=too-many-locals nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, content_md5: Optional[bytes] = None, file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - optional_content_length: Optional[int] = None, + content_length: Optional[int] = None, structured_body_type: Optional[str] = None, structured_content_length: Optional[int] = None, **kwargs: Any @@ -1233,10 +1234,8 @@ async def create( # pylint: disable=too-many-locals :param optional_body: Initial data. Default value is None. :type optional_body: bytes - :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. - Required. - :paramtype content_length: int + :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 @@ -1311,9 +1310,10 @@ async def create( # pylint: disable=too-many-locals "Restore". Default value is None. :paramtype file_property_semantics: str or ~azure.storage.fileshare.models.FilePropertySemantics - :keyword optional_content_length: Optional. Specifies the content length of the file. Default - value is None. - :paramtype optional_content_length: int + :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. @@ -1347,7 +1347,7 @@ async def create( # pylint: disable=too-many-locals _content = optional_body _request = build_file_create_request( - content_length=content_length, + file_content_length=file_content_length, timeout=timeout, file_content_type=file_content_type, file_content_encoding=file_content_encoding, @@ -1372,7 +1372,7 @@ async def create( # pylint: disable=too-many-locals nfs_file_type=nfs_file_type, content_md5=content_md5, file_property_semantics=file_property_semantics, - optional_content_length=optional_content_length, + content_length=content_length, structured_body_type=structured_body_type, structured_content_length=structured_content_length, file_type=file_type, @@ -2092,6 +2092,7 @@ async def set_metadata( 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( @@ -2717,6 +2718,7 @@ async def upload_range_from_url( # pylint: disable=too-many-locals 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") ) @@ -4393,7 +4395,7 @@ async def get_properties( 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( - "str", response.headers.get("x-ms-access-tier-change-time") + "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") 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 index bbb76cf01ad1..3bcab94009b4 100644 --- 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 @@ -1939,10 +1939,10 @@ class StorageServiceProperties(_Model): :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 cors: The set of CORS rules. - :vartype cors: ~azure.storage.fileshare._generated.models.CorsRule :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( @@ -1957,16 +1957,16 @@ class StorageServiceProperties(_Model): xml={"attribute": False, "name": "MinuteMetrics", "text": False, "unwrapped": False}, ) """A summary of request statistics grouped by API in minute aggregates for files.""" - 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.""" 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} @@ -1976,8 +1976,8 @@ def __init__( *, hour_metrics: Optional["_models.Metrics"] = None, minute_metrics: Optional["_models.Metrics"] = None, - cors: Optional[list["_models.CorsRule"]] = None, protocol: Optional["_models.ShareProtocolSettings"] = None, + cors: Optional[list["_models.CorsRule"]] = None, ) -> None: ... @overload 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 index 7ec09992d382..6a2d91af9087 100644 --- 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 @@ -466,7 +466,7 @@ def build_directory_rename_request( def build_file_create_request( # pylint: disable=too-many-locals,too-many-statements,too-many-branches *, - content_length: int, + file_content_length: int, timeout: Optional[int] = None, file_content_type: Optional[str] = None, file_content_encoding: Optional[str] = None, @@ -491,7 +491,7 @@ def build_file_create_request( # pylint: disable=too-many-locals,too-many-state nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, content_md5: Optional[bytes] = None, file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - optional_content_length: Optional[int] = None, + content_length: Optional[int] = None, structured_body_type: Optional[str] = None, structured_content_length: Optional[int] = None, **kwargs: Any @@ -513,7 +513,7 @@ def build_file_create_request( # pylint: disable=too-many-locals,too-many-state _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("content_length", content_length, "int") + _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") @@ -567,8 +567,8 @@ def build_file_create_request( # pylint: disable=too-many-locals,too-many-state _headers["x-ms-file-property-semantics"] = _SERIALIZER.header( "file_property_semantics", file_property_semantics, "str" ) - if optional_content_length is not None: - _headers["Content-Length"] = _SERIALIZER.header("optional_content_length", optional_content_length, "int") + 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: @@ -2846,6 +2846,7 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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( @@ -3367,7 +3368,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals self, optional_body: Optional[bytes] = None, *, - content_length: int, + file_content_length: int, timeout: Optional[int] = None, file_content_type: Optional[str] = None, file_content_encoding: Optional[str] = None, @@ -3392,7 +3393,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals nfs_file_type: Optional[Union[str, _models.NfsFileType]] = None, content_md5: Optional[bytes] = None, file_property_semantics: Optional[Union[str, _models.FilePropertySemantics]] = None, - optional_content_length: Optional[int] = None, + content_length: Optional[int] = None, structured_body_type: Optional[str] = None, structured_content_length: Optional[int] = None, **kwargs: Any @@ -3401,10 +3402,8 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals :param optional_body: Initial data. Default value is None. :type optional_body: bytes - :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. - Required. - :paramtype content_length: int + :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 @@ -3479,9 +3478,10 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals "Restore". Default value is None. :paramtype file_property_semantics: str or ~azure.storage.fileshare.models.FilePropertySemantics - :keyword optional_content_length: Optional. Specifies the content length of the file. Default - value is None. - :paramtype optional_content_length: int + :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. @@ -3515,7 +3515,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals _content = optional_body _request = build_file_create_request( - content_length=content_length, + file_content_length=file_content_length, timeout=timeout, file_content_type=file_content_type, file_content_encoding=file_content_encoding, @@ -3540,7 +3540,7 @@ def create( # pylint: disable=inconsistent-return-statements,too-many-locals nfs_file_type=nfs_file_type, content_md5=content_md5, file_property_semantics=file_property_semantics, - optional_content_length=optional_content_length, + content_length=content_length, structured_body_type=structured_body_type, structured_content_length=structured_content_length, file_type=file_type, @@ -4260,6 +4260,7 @@ def set_metadata( # pylint: disable=inconsistent-return-statements 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( @@ -4885,6 +4886,7 @@ def upload_range_from_url( # pylint: disable=inconsistent-return-statements,too 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") ) @@ -6561,7 +6563,7 @@ def get_properties( # pylint: disable=inconsistent-return-statements 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( - "str", response.headers.get("x-ms-access-tier-change-time") + "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") From 53d41f599edd77ce42c9452b6f3e65980d87dff6 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 22 Apr 2026 10:39:06 -0700 Subject: [PATCH 31/45] regen renamed a param Co-authored-by: Copilot --- .../azure/storage/fileshare/_file_client.py | 4 ++-- .../azure/storage/fileshare/aio/_file_client_async.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) 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 30f3fe63623c..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 @@ -499,7 +499,7 @@ def create_file( return cast( Dict[str, Any], self._client.file.create( - content_length=size, + 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), @@ -509,7 +509,7 @@ def create_file( file_permission_key=permission_key, **file_http_headers, optional_body=data, - optional_content_length=len(data) if data is not None else None, + content_length=len(data) if data is not None else None, lease_id=access_conditions, headers=headers, timeout=timeout, 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 72ec476a0438..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 @@ -514,7 +514,7 @@ async def create_file( return cast( Dict[str, Any], await self._client.file.create( - content_length=size, + 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), @@ -524,7 +524,7 @@ async def create_file( file_permission_key=permission_key, **file_http_headers, optional_body=data, - optional_content_length=len(data) if data is not None else None, + content_length=len(data) if data is not None else None, lease_id=access_conditions, headers=headers, timeout=timeout, From cfa946ba8a27d6b996c440e81ced1f81a3f6b044 Mon Sep 17 00:00:00 2001 From: l0lawrence Date: Mon, 27 Apr 2026 08:58:09 -0700 Subject: [PATCH 32/45] Align _shared upload helpers with azure-storage-blob TSP migration Port changes from azure-storage-blob storageblob3 branch to keep _shared files consistent across Storage packages: - request_handlers.py: collapse split string literals - uploads.py / uploads_async.py: switch BlockBlob/PageBlob/AppendBlob ChunkUploader callers to keyword args and to the new etag / match_condition / append_position kwarg names; pop those kwargs in upload_data_chunks and upload_substream_blocks when running in parallel. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../fileshare/_shared/request_handlers.py | 4 +-- .../storage/fileshare/_shared/uploads.py | 28 +++++++++++-------- .../fileshare/_shared/uploads_async.py | 26 ++++++++++------- 3 files changed, 35 insertions(+), 23 deletions(-) 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/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), From 3fad009fd71b877a784105f1c79327e1de438a0a Mon Sep 17 00:00:00 2001 From: l0lawrence Date: Fri, 1 May 2026 10:50:39 -0700 Subject: [PATCH 33/45] Fix FileProperty datetime fields: declare as str, not RFC7231 datetime The wire format for creationTime/lastAccessTime/lastWriteTime/changeTime is ISO 8601, not RFC 7231 (only Last-Modified is RFC 7231). Declaring them as Optional[datetime.datetime] with format="rfc7231" causes the XML deserializer to fail and leave a raw xml.etree.ElementTree.Element in _data, which crashes JSON serialization downstream (Azure CLI). Match the legacy SDK behavior by declaring these fields as Optional[str]. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../fileshare/_generated/models/_models.py | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) 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 index 3bcab94009b4..f58d1ee830ca 100644 --- 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 @@ -462,13 +462,13 @@ class FileProperty(_Model): call Get File Properties. Required. :vartype content_length: int :ivar creation_time: The creation time. - :vartype creation_time: ~datetime.datetime + :vartype creation_time: str :ivar last_access_time: The last access time. - :vartype last_access_time: ~datetime.datetime + :vartype last_access_time: str :ivar last_write_time: The last write time. - :vartype last_write_time: ~datetime.datetime + :vartype last_write_time: str :ivar change_time: The change time. - :vartype change_time: ~datetime.datetime + :vartype change_time: str :ivar last_modified: The last modified time. :vartype last_modified: ~datetime.datetime :ivar etag: The ETag of the file. @@ -484,31 +484,27 @@ class FileProperty(_Model): 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[datetime.datetime] = rest_field( + creation_time: Optional[str] = rest_field( name="creationTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc7231", xml={"attribute": False, "name": "CreationTime", "text": False, "unwrapped": False}, ) """The creation time.""" - last_access_time: Optional[datetime.datetime] = rest_field( + last_access_time: Optional[str] = rest_field( name="lastAccessTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc7231", xml={"attribute": False, "name": "LastAccessTime", "text": False, "unwrapped": False}, ) """The last access time.""" - last_write_time: Optional[datetime.datetime] = rest_field( + last_write_time: Optional[str] = rest_field( name="lastWriteTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc7231", xml={"attribute": False, "name": "LastWriteTime", "text": False, "unwrapped": False}, ) """The last write time.""" - change_time: Optional[datetime.datetime] = rest_field( + change_time: Optional[str] = rest_field( name="changeTime", visibility=["read", "create", "update", "delete", "query"], - format="rfc7231", xml={"attribute": False, "name": "ChangeTime", "text": False, "unwrapped": False}, ) """The change time.""" @@ -532,10 +528,10 @@ 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, + 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: ... From 83c2a38469d2d6212e1a34f2942883cf73921cb2 Mon Sep 17 00:00:00 2001 From: l0lawrence Date: Fri, 1 May 2026 11:29:05 -0700 Subject: [PATCH 34/45] wip changes from running against azure cli Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../fileshare/_generated/models/_patch.py | 47 ++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-) 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..f52b0dcf90b0 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 @@ -6,11 +6,56 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List +from typing import Any, List + +from .._utils.model_base import Model as _Model, _MyMutableMapping __all__: List[str] = [] # Add all objects you want publicly available to users at this package level +# --------------------------------------------------------------------------- +# 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 + + def patch_sdk(): """Do not remove from this file. From 7e2d020a5d316a37f797eefb5c16bed9e9af8c0e Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 6 May 2026 09:42:28 -0700 Subject: [PATCH 35/45] also patch here for backcompat --- .../fileshare/_generated/models/_patch.py | 230 +++++++- .../azure/storage/fileshare/_models.py | 529 +++++++++--------- 2 files changed, 496 insertions(+), 263 deletions(-) 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 f52b0dcf90b0..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,16 +1,229 @@ -# ------------------------------------ -# 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 Any, List +import xml.etree.ElementTree as ET +from typing import Any, Callable, List, Optional -from .._utils.model_base import Model as _Model, _MyMutableMapping +from .._utils.model_base import Model as _Model, _MyMutableMapping, _RestField, _deserialize -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + +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) # --------------------------------------------------------------------------- @@ -56,6 +269,9 @@ def _patched_namedtuple_asdict(self) -> dict: _Model._asdict = _patched_namedtuple_asdict +__all__: List[str] = [] + + def patch_sdk(): """Do not remove from this file. 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 a5316bef7c81..c3e709e0867a 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,4 +1,3 @@ -# 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,7 +6,10 @@ # 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 @@ -38,8 +40,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): @@ -55,10 +57,17 @@ class RetentionPolicy(GeneratedRetentionPolicy): All data older than this value will be deleted. """ + enabled: bool = False + """Indicates whether a retention policy is enabled for the storage service.""" + days: Optional[int] = None + """Indicates the number of days that metrics or logging or soft-deleted data should be retained. + All data older than this value will be deleted.""" + def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: - if enabled and days is None: + self.enabled = enabled + self.days = days + if self.enabled and (self.days is None): raise ValueError("If policy is enabled, 'days' must be specified.") - super().__init__(enabled=enabled, days=days) @classmethod def _from_generated(cls, generated): @@ -86,13 +95,20 @@ class Metrics(GeneratedMetrics): Determines how long the associated data should persist. """ + version: str = '1.0' + """The version of Storage Analytics to configure.""" + enabled: bool = False + """Indicates whether metrics are enabled for the File service.""" + include_apis: bool + """Indicates whether metrics should generate summary statistics for called API operations.""" + retention_policy: RetentionPolicy = RetentionPolicy() + """Determines how long the associated data should persist.""" + def __init__(self, **kwargs: Any) -> None: - super().__init__( - version=kwargs.get("version", "1.0"), - enabled=kwargs.get("enabled", False), - include_apis=kwargs.get("include_apis"), - 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): @@ -102,9 +118,7 @@ def _from_generated(cls, generated): version=generated.version, enabled=generated.enabled, include_apis=generated.include_apis, - retention_policy=RetentionPolicy._from_generated( # pylint: disable=protected-access - generated.retention_policy - ), + retention_policy=RetentionPolicy._from_generated(generated.retention_policy) # pylint: disable=protected-access ) @@ -138,14 +152,27 @@ class CorsRule(GeneratedCorsRule): preflight response. """ + allowed_origins: str + """The comma-delimited string representation of the list of origin domains + that will be allowed via CORS, or "*" to allow all domains.""" + allowed_methods: str + """The comma-delimited string representation of the list of HTTP methods + that are allowed to be executed by the origin.""" + allowed_headers: str + """The comma-delimited string representation of the list of headers + allowed to be a part of the cross-origin request.""" + exposed_headers: str + """The comma-delimited string representation of the list of response + headers to expose to CORS clients.""" + max_age_in_seconds: int + """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: - super().__init__( - allowed_origins=",".join(allowed_origins), - allowed_methods=",".join(allowed_methods), - allowed_headers=",".join(kwargs.get("allowed_headers", [])), - exposed_headers=",".join(kwargs.get("exposed_headers", [])), - 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]]: @@ -182,8 +209,11 @@ class SmbMultichannel(GeneratedSmbMultichannel): :keyword bool enabled: If SMB Multichannel is enabled. """ - def __init__(self, *, enabled: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - super().__init__(enabled=enabled) + enabled: bool + """If SMB Multichannel is enabled.""" + + def __init__(self, *, enabled: bool, **kwargs: Any) -> None: + self.enabled = enabled class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): @@ -192,8 +222,11 @@ class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): :keyword bool required: If encryption in transit is required. """ - def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - super().__init__(required=required) + required: bool + """If encryption in transit is enabled.""" + + def __init__(self, *, required: bool, **kwargs: Any) -> None: + self.required = required class ShareSmbSettings(GeneratedShareSmbSettings): @@ -203,16 +236,22 @@ class ShareSmbSettings(GeneratedShareSmbSettings): :keyword SmbEncryptionInTransit encryption_in_transit: Sets the encryption in transit settings. """ - def __init__( # pylint: disable=unused-argument + multichannel: Optional[SmbMultichannel] + """Sets the multichannel settings.""" + encryption_in_transit: Optional[SmbEncryptionInTransit] + """Sets the encryption in transit settings.""" + + def __init__( self, *, multichannel: Optional[SmbMultichannel] = None, encryption_in_transit: Optional[SmbEncryptionInTransit] = None, - **kwargs: Any, + **kwargs: Any ) -> None: - if multichannel is None and encryption_in_transit is None: + self.multichannel = multichannel + self.encryption_in_transit = encryption_in_transit + if self.multichannel is None and self.encryption_in_transit is None: raise ValueError("The value 'multichannel' or 'encryption_in_transit' must be specified.") - super().__init__(multichannel=multichannel, encryption_in_transit=encryption_in_transit) class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): @@ -221,8 +260,11 @@ class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): :keyword bool required: If encryption in transit is required. """ - def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - super().__init__(required=required) + required: bool + """If encryption in transit is enabled.""" + + def __init__(self, *, required: bool, **kwargs: Any) -> None: + self.required = required class ShareNfsSettings(GeneratedShareNfsSettings): @@ -231,10 +273,11 @@ class ShareNfsSettings(GeneratedShareNfsSettings): :keyword NfsEncryptionInTransit encryption_in_transit: Sets the encryption in transit settings. """ - def __init__( - self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any # pylint: disable=unused-argument - ) -> None: - super().__init__(encryption_in_transit=encryption_in_transit) + encryption_in_transit: NfsEncryptionInTransit + """Sets the encryption in transit settings.""" + + def __init__(self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any) -> None: + self.encryption_in_transit = encryption_in_transit class ShareProtocolSettings(GeneratedShareProtocolSettings): @@ -246,16 +289,22 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): :keyword ShareNfsSettings nfs: Sets NFS settings. """ - def __init__( # pylint: disable=unused-argument + smb: Optional[ShareSmbSettings] + """Sets the SMB settings.""" + nfs: Optional[ShareNfsSettings] + """Sets the NFS settings.""" + + def __init__( self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, - **kwargs: Any, + **kwargs: Any ) -> None: - if smb is None and nfs is None: + self.smb = smb + self.nfs = nfs + if self.smb is None and self.nfs is None: raise ValueError("The value 'smb' or 'nfs' must be specified.") - super().__init__(smb=smb, nfs=nfs) @classmethod def _from_generated(cls, generated): @@ -297,20 +346,22 @@ 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 @@ -328,11 +379,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) @@ -383,17 +434,22 @@ class AccessPolicy(GenAccessPolicy): :type start: ~datetime.datetime or str """ - start: Optional[Union["datetime", str]] # type: ignore[assignment] - expiry: Optional[Union["datetime", str]] # type: ignore[assignment] - permission: Optional[Union[ShareSasPermissions, str]] # type: ignore[assignment] + permission: Optional[Union[ShareSasPermissions, str]] # type: ignore [assignment] + """The permissions associated with the shared access signature. The user is restricted to + operations allowed by the permissions.""" + expiry: Optional[Union["datetime", str]] # type: ignore [assignment] + """The time at which the shared access signature becomes invalid.""" + start: Optional[Union["datetime", str]] # type: ignore [assignment] + """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: - super().__init__(start=start, expiry=expiry, permission=permission) # type: ignore[arg-type] + self.start = start + self.expiry = expiry + self.permission = permission class LeaseProperties(DictMixin): @@ -407,9 +463,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): @@ -460,21 +516,20 @@ 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, cache_control: Optional[str] = None, content_md5: Optional[bytearray] = None, - **kwargs: Any, + **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): @@ -549,40 +604,39 @@ 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 = 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" - ) + 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')) @classmethod def _from_generated(cls, generated): @@ -604,11 +658,8 @@ 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 @@ -617,11 +668,9 @@ 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 @@ -650,14 +699,15 @@ 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 @@ -674,8 +724,7 @@ 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) @@ -685,9 +734,7 @@ 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 @@ -728,20 +775,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): @@ -778,10 +825,14 @@ 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 @@ -795,16 +846,13 @@ 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 @@ -836,8 +884,7 @@ 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, @@ -846,7 +893,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 @@ -858,22 +905,20 @@ 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: @@ -897,9 +942,8 @@ 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 @@ -941,40 +985,31 @@ 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): @@ -1022,14 +1057,15 @@ 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 @@ -1046,8 +1082,7 @@ 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) @@ -1056,16 +1091,8 @@ 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) # 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 - ] - ) + 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 return self._response.next_marker or None, self.current_page @@ -1116,14 +1143,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): @@ -1199,54 +1226,42 @@ 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] - last_modified = kwargs.get("Last-Modified") - if isinstance(last_modified, str): - last_modified = Deserializer.deserialize_rfc(last_modified) - self.last_modified = 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): @@ -1267,7 +1282,6 @@ def _from_generated(cls, generated): class ShareProtocols(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Enabled protocols on the share""" - SMB = "SMB" NFS = "NFS" @@ -1297,17 +1311,20 @@ 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 @@ -1325,10 +1342,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) @@ -1337,8 +1354,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 } From 57cf512b28f9054734433f258b706f6277ccf661 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 13 May 2026 15:20:57 -0700 Subject: [PATCH 36/45] regen --- .../_generated/aio/operations/_operations.py | 1 - .../_generated/operations/_operations.py | 1 - .../azure/storage/fileshare/_models.py | 417 ++++++++++-------- 3 files changed, 222 insertions(+), 197 deletions(-) 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 index 1ee96a47a469..79d9adc0c19d 100644 --- 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 @@ -1589,7 +1589,6 @@ async def download( 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")) 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 index 6a2d91af9087..83f32b15d5d3 100644 --- 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 @@ -3757,7 +3757,6 @@ def download( 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")) 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..67bfb44fb673 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( + generated.retention_policy + ), # pylint: disable=protected-access ) @@ -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]]: @@ -295,11 +295,7 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): """Sets the NFS settings.""" def __init__( - self, - *, - smb: Optional[ShareSmbSettings] = None, - nfs: Optional[ShareNfsSettings] = None, - **kwargs: Any + self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any ) -> None: self.smb = smb self.nfs = nfs @@ -346,22 +342,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 +373,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 +437,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 +458,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 +511,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 +520,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 +600,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 +655,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 +668,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 +701,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 +725,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 +736,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 +779,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 +829,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 +846,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 +887,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 +897,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 +909,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 +948,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 +992,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 +1073,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,7 +1097,8 @@ 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) @@ -1091,8 +1107,12 @@ 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) 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 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 } From 273da744412d1b567421880c4aa0824a9aa7ff61 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 14 May 2026 11:07:38 -0700 Subject: [PATCH 37/45] Fix pylint: relocate disable comments in _models.py - Move 'protected-access' disables from closing-bracket lines onto the lines where '_from_generated' is actually accessed (Metrics, SharePropertiesPaged, HandlesPaged). - Use scoped 'disable/enable=protected-access' block in DirectoryPropertiesPaged._extract_data_cb (two accesses too long to carry inline disables under the 120-char limit). - Add 'unused-argument' disables to the backcompat **kwargs catch-all __init__ methods on SmbMultichannel, SmbEncryptionInTransit, ShareSmbSettings, NfsEncryptionInTransit, ShareNfsSettings, and ShareProtocolSettings. No logic changes. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../azure/storage/fileshare/_models.py | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) 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 67bfb44fb673..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 @@ -116,9 +116,9 @@ def _from_generated(cls, generated): version=generated.version, enabled=generated.enabled, include_apis=generated.include_apis, - retention_policy=RetentionPolicy._from_generated( + retention_policy=RetentionPolicy._from_generated( # pylint: disable=protected-access generated.retention_policy - ), # pylint: disable=protected-access + ), ) @@ -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,7 +296,7 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): nfs: Optional[ShareNfsSettings] """Sets the NFS settings.""" - def __init__( + def __init__( # pylint: disable=unused-argument self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any ) -> None: self.smb = smb @@ -737,8 +739,8 @@ def _extract_data_cb(self, get_next_return): 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 + 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 @@ -854,8 +856,8 @@ def _get_next_cb(self, continuation_token): 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 + 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 @@ -1103,16 +1105,14 @@ def _get_next_cb(self, continuation_token): 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 From 38117b907c1fb101ac6bfb5168eb648df0ad8056 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 10:26:44 -0700 Subject: [PATCH 38/45] client docstring --- .../storage/fileshare/_generated/_patch.py | 47 ++++++++++--------- .../fileshare/_generated/aio/_patch.py | 47 ++++++++++--------- 2 files changed, 50 insertions(+), 44 deletions(-) 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 2cf4b1394be1..85823baef25e 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 @@ -11,8 +11,11 @@ from azure.core import PipelineClient from azure.core.pipeline import Pipeline, PipelineRequest +from azure.core.pipeline import policies from azure.core.pipeline.policies import SansIOHTTPPolicy +from ._utils.serialization import Deserializer, Serializer +from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations from ._client import FileClient as GeneratedFileClient from ._configuration import FileClientConfiguration as GeneratedFileClientConfiguration @@ -30,17 +33,19 @@ def on_request(self, request: PipelineRequest) -> None: class FileClientConfiguration(GeneratedFileClientConfiguration): - """Configuration for FileClient that allows optional credentials. + """Configuration for FileClient. - This class overrides the generated configuration to allow None credentials - for anonymous access or when a pre-built pipeline handles auth. + Note that all parameters used to create this instance are saved as instance + attributes. :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. + :param credential: Credential used to authenticate requests to the service. :type credential: ~azure.core.credentials.TokenCredential or None - :keyword version: Specifies the version of the operation to use for this request. + :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 """ @@ -60,29 +65,31 @@ def __init__(self, url: str, credential: Optional["TokenCredential"] = None, **k self._configure(**kwargs) -class AzureFileStorage(GeneratedFileClient): - """Subclass of the generated FileClient that allows optional credentials, - accepts a pre-built pipeline, and injects the RangeHeaderPolicy. +class FileClient(GeneratedFileClient): + """Azure File Storage provides scalable file shares in the cloud using SMB and NFS protocols. - :param url: The URL of the service account, share, directory or file. + :ivar directory: DirectoryOperations operations + :vartype directory: azure.storage.fileshare.operations.DirectoryOperations + :ivar file: FileOperations operations + :vartype file: azure.storage.fileshare.operations.FileOperations + :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 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. + :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, 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) @@ -124,10 +131,6 @@ def __init__( 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"] 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 eb56c0b33775..414a023364ae 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 @@ -12,7 +12,10 @@ from azure.core import AsyncPipelineClient from azure.core.pipeline import AsyncPipeline, PipelineRequest from azure.core.pipeline.policies import SansIOHTTPPolicy +from azure.core.pipeline import policies +from .._utils.serialization import Deserializer, Serializer +from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations from ._client import FileClient as GeneratedFileClient from ._configuration import FileClientConfiguration as GeneratedFileClientConfiguration @@ -30,17 +33,19 @@ def on_request(self, request: PipelineRequest) -> None: class FileClientConfiguration(GeneratedFileClientConfiguration): - """Configuration for FileClient that allows optional credentials. + """Configuration for FileClient. - This class overrides the generated configuration to allow None credentials - for anonymous access or when a pre-built pipeline handles auth. + Note that all parameters used to create this instance are saved as instance + attributes. :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. + :param credential: Credential used to authenticate requests to the service. :type credential: ~azure.core.credentials_async.AsyncTokenCredential or None - :keyword version: Specifies the version of the operation to use for this request. + :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 """ @@ -60,29 +65,31 @@ def __init__(self, url: str, credential: Optional["AsyncTokenCredential"] = None self._configure(**kwargs) -class AzureFileStorage(GeneratedFileClient): - """Subclass of the generated FileClient that allows optional credentials, - accepts a pre-built pipeline, and injects the RangeHeaderPolicy. +class FileClient(GeneratedFileClient): + """Azure File Storage provides scalable file shares in the cloud using SMB and NFS protocols. - :param url: The URL of the service account, share, directory or file. + :ivar directory: DirectoryOperations operations + :vartype directory: azure.storage.fileshare.aio.operations.DirectoryOperations + :ivar file: FileOperations operations + :vartype file: azure.storage.fileshare.aio.operations.FileOperations + :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 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. + :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, 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) @@ -123,10 +130,6 @@ def __init__( 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"] From 8a85b35493ba68561e011db54052044f11099e3d Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 15 May 2026 10:30:20 -0700 Subject: [PATCH 39/45] todo --- .../azure/storage/fileshare/_generated/models/_patch.py | 1 + 1 file changed, 1 insertion(+) 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 257980819201..5cc77508168d 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 @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ +# TODO: Waiting for emitter release with perf improvements before editing the patch import xml.etree.ElementTree as ET from typing import Any, Callable, List, Optional From 9b88da3e93700e73d22bab016ac9f5fd0a3f6427 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 20 May 2026 10:08:04 -0700 Subject: [PATCH 40/45] regen --- .../apiview-properties.json | 3 ++- .../storage/fileshare/_generated/_client.py | 12 ++++++--- .../fileshare/_generated/_configuration.py | 5 ++-- .../storage/fileshare/_generated/_patch.py | 1 + .../fileshare/_generated/_utils/model_base.py | 26 ++++++++++++++----- .../_generated/_utils/serialization.py | 6 ++++- .../fileshare/_generated/aio/_client.py | 12 ++++++--- .../_generated/aio/_configuration.py | 5 ++-- .../fileshare/_generated/aio/_patch.py | 1 + .../_generated/aio/operations/_patch.py | 1 - .../fileshare/_generated/models/_patch.py | 1 + .../azure/storage/fileshare/_serialize.py | 4 +-- .../azure/storage/fileshare/_share_client.py | 1 - .../storage/fileshare/_shared/constants.py | 1 - .../fileshare/_shared/request_handlers.py | 1 - .../fileshare/_shared/response_handlers.py | 1 - .../storage/fileshare/_shared/uploads.py | 1 - .../azure/storage/fileshare/aio/__init__.py | 1 - .../azure-storage-file-share/pyproject.toml | 5 ++-- .../samples/file_samples_client_async.py | 1 - .../tests/encryption_test_helper.py | 1 - .../tests/test_directory.py | 22 ++++++++-------- .../tests/test_directory_async.py | 18 ++++++------- .../tests/test_file_api_version.py | 1 - .../tests/test_file_api_version_async.py | 1 - .../tests/test_file_client.py | 1 - .../tests/test_file_client_async.py | 1 - .../test_file_service_properties_async.py | 1 - .../tests/test_handle.py | 1 - .../tests/test_handle_async.py | 1 - .../tests/test_nfs.py | 1 - .../tests/test_nfs_async.py | 1 - .../tsp-location.yaml | 4 +-- 33 files changed, 79 insertions(+), 64 deletions(-) diff --git a/sdk/storage/azure-storage-file-share/apiview-properties.json b/sdk/storage/azure-storage-file-share/apiview-properties.json index 1408a4caf6a8..ebaba2c5f7d4 100644 --- a/sdk/storage/azure-storage-file-share/apiview-properties.json +++ b/sdk/storage/azure-storage-file-share/apiview-properties.json @@ -156,5 +156,6 @@ "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" - } + }, + "CrossLanguageVersion": "fdd35c41a0ed" } \ No newline at end of file diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py index 6540b3fde6f6..91c54c5094ef 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, TYPE_CHECKING -from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies @@ -18,6 +18,11 @@ from ._utils.serialization import Deserializer, Serializer from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: from azure.core.credentials import TokenCredential @@ -39,8 +44,9 @@ class FileClient: # pylint: disable=client-accepts-api-version-keyword :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. + are "2026-06-06" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype version: str """ 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 a2935329dbae..ff0fbd76c9ce 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 @@ -28,8 +28,9 @@ class FileClientConfiguration: # pylint: disable=too-many-instance-attributes :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. + are "2026-06-06" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype version: str """ 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 85823baef25e..64509fb03024 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 @@ -7,6 +7,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + from typing import Any, Optional, TYPE_CHECKING from azure.core import PipelineClient 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 index eef4e52ed1a0..54f247904997 100644 --- 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 @@ -23,14 +23,19 @@ 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 +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -595,11 +600,7 @@ 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 - } + dict_to_pass: dict[str, typing.Any] = {} if args: if isinstance(args[0], ET.Element): dict_to_pass.update(self._init_from_xml(args[0])) @@ -619,6 +620,14 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if v is not None } ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) super().__init__(dict_to_pass) def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: @@ -1129,7 +1138,10 @@ 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) + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None if item is None: return item if self._is_model: 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 81ec1de5922b..954bf7ebffa7 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 @@ -39,11 +39,15 @@ import xml.etree.ElementTree as ET import isodate # type: ignore -from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") JSON = MutableMapping[str, Any] diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py index cbe7736f7651..11aa09210c9c 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_generated/aio/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, Awaitable, TYPE_CHECKING -from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies @@ -18,6 +18,11 @@ from ._configuration import FileClientConfiguration from .operations import DirectoryOperations, FileOperations, ServiceOperations, ShareOperations +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential @@ -39,8 +44,9 @@ class FileClient: # pylint: disable=client-accepts-api-version-keyword :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. + are "2026-06-06" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype version: str """ 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 139d6fcee5c8..e0f68c0e30fd 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 @@ -28,8 +28,9 @@ class FileClientConfiguration: # pylint: disable=too-many-instance-attributes :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. + are "2026-06-06" and None. Default value is None. If not set, the operation's default API + version will be used. Note that overriding this default value may result in unsupported + behavior. :paramtype version: str """ 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 414a023364ae..af3f434c7d47 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 @@ -7,6 +7,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + from typing import Any, Optional, TYPE_CHECKING from azure.core import AsyncPipelineClient 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 87676c65a8f0..ea765788358a 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 @@ -8,7 +8,6 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ - __all__: list[str] = [] # Add all objects you want publicly available to users at this package level 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 5cc77508168d..a0cd1431e1bf 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 @@ -8,6 +8,7 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + # TODO: Waiting for emitter release with perf improvements before editing the patch import xml.etree.ElementTree as ET from typing import Any, Callable, List, Optional 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 1f362734a901..b53ccf9fecc9 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 @@ -101,7 +101,7 @@ def get_access_conditions(lease: Optional[Union["ShareLeaseClient", "ShareLeaseC def get_source_access_conditions( - lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]] + lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]], ) -> Optional[str]: """Extract source_lease_id from a lease client or string. Returns the lease_id string or None. @@ -118,7 +118,7 @@ def get_source_access_conditions( def get_dest_access_conditions( - lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]] + lease: Optional[Union["ShareLeaseClient", "ShareLeaseClientAsync", str]], ) -> Optional[str]: """Extract destination_lease_id from a lease client or string. Returns the lease_id string or None. 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 d4398fa4c4e6..882471d3ebd3 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 @@ -27,7 +27,6 @@ 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 - if TYPE_CHECKING: from azure.core.credentials import AzureNamedKeyCredential, AzureSasCredential, TokenCredential from ._models import AccessPolicy, DirectoryProperties, FileProperties, ShareProperties diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/constants.py b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/constants.py index 2bf865acf343..c9c2ba8f74d0 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/constants.py +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_shared/constants.py @@ -6,7 +6,6 @@ from .._serialize import _SUPPORTED_API_VERSIONS - X_MS_VERSION = _SUPPORTED_API_VERSIONS[-1] # Connection defaults 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 8bef3c487b30..d8c71d33a961 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 @@ -12,7 +12,6 @@ import isodate - _LOGGER = logging.getLogger(__name__) _REQUEST_DELIMITER_PREFIX = "batch_" 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 19f9d1086c66..24855e202642 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 @@ -22,7 +22,6 @@ from .models import get_enum_value, StorageErrorCode, UserDelegationKey from .parser import _to_utc_datetime - SV_DOCS_URL = "https://learn.microsoft.com/rest/api/storageservices/versioning-for-the-azure-storage-services" _LOGGER = logging.getLogger(__name__) 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 9c55e82257d2..b2dc44770eec 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 @@ -16,7 +16,6 @@ from .request_handlers import get_length from .response_handlers import return_response_headers - _LARGE_BLOB_UPLOAD_MAX_READ_BUFFER_SIZE = 4 * 1024 * 1024 _ERROR_VALUE_SHOULD_BE_SEEKABLE_STREAM = "{0} should be a seekable file-like/io.IOBase type stream object." 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 489635c591d1..3cdd03d25573 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 @@ -10,7 +10,6 @@ from ._share_service_client_async import ShareServiceClient from ._lease_async import ShareLeaseClient - __all__ = [ "ShareFileClient", "ShareDirectoryClient", diff --git a/sdk/storage/azure-storage-file-share/pyproject.toml b/sdk/storage/azure-storage-file-share/pyproject.toml index 8bcd9b911dfa..16a28d216941 100644 --- a/sdk/storage/azure-storage-file-share/pyproject.toml +++ b/sdk/storage/azure-storage-file-share/pyproject.toml @@ -21,13 +21,12 @@ classifiers = [ "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" +requires-python = ">=3.10" keywords = ["azure", "azure sdk"] dependencies = [ @@ -42,7 +41,7 @@ dynamic = [ [project.optional-dependencies] aio = [ - "azure-core[aio]>=1.38.3", + "azure-core[aio]>=1.38.3", ] [project.urls] 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 e7388945dd49..54099136a919 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 @@ -21,7 +21,6 @@ 2) STORAGE_ACCOUNT_NAME - the name of the storage account """ - import asyncio import os import sys 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 23cf5d7aeebc..f0144365c315 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 @@ -16,7 +16,6 @@ aes_key_unwrap, ) - _ERROR_UNKNOWN_KEY_WRAP_ALGORITHM = "Unknown keywrap algorithm specified. Supported algorithm: A256KW." 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 419a42afb8be..2c4ed50a0530 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_directory.py +++ b/sdk/storage/azure-storage-file-share/tests/test_directory.py @@ -848,18 +848,18 @@ 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.create_subdirectory("subdir1\uFFFE") - directory.upload_file("file\uFFFE", "data1") + directory = share_client.create_directory("directory\ufffe") + directory.create_subdirectory("subdir1\ufffe") + directory.upload_file("file\ufffe", "data1") # Act list_dir = list(directory.list_directories_and_files()) # Assert assert len(list_dir) == 2 - assert list_dir[0]["name"] == "subdir1\uFFFE" + 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]["name"] == "file\ufffe" assert list_dir[1]["is_directory"] == False @FileSharePreparer() @@ -870,18 +870,18 @@ 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.create_subdirectory("\uFFFFsubdir1") - directory.upload_file("\uFFFFfile", "data1") + directory = share_client.create_directory("\uffffdirectory") + directory.create_subdirectory("\uffffsubdir1") + directory.upload_file("\ufffffile", "data1") # Act - list_dir = list(directory.list_directories_and_files(name_starts_with="\uFFFF")) + list_dir = list(directory.list_directories_and_files(name_starts_with="\uffff")) # Assert assert len(list_dir) == 2 - assert list_dir[0]["name"] == "\uFFFFsubdir1" + assert list_dir[0]["name"] == "\uffffsubdir1" assert list_dir[0]["is_directory"] == True - assert list_dir[1]["name"] == "\uFFFFfile" + assert list_dir[1]["name"] == "\ufffffile" assert list_dir[1]["is_directory"] == False @FileSharePreparer() 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 adadd95b261e..a1fef26ce12a 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 @@ -897,9 +897,9 @@ 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 @@ -909,9 +909,9 @@ 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]["name"] == "subdir1\ufffe" assert list_dir[0]["is_directory"] == True - assert list_dir[1]["name"] == "file1\uFFFE" + assert list_dir[1]["name"] == "file1\ufffe" assert list_dir[1]["is_directory"] == False @FileSharePreparer() @@ -923,21 +923,21 @@ 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 = [] - async for d in directory.list_directories_and_files(name_starts_with="\uFFFF"): + async for d in directory.list_directories_and_files(name_starts_with="\uffff"): list_dir.append(d) # Assert assert len(list_dir) == 2 - assert list_dir[0]["name"] == "\uFFFFsubdir1" + assert list_dir[0]["name"] == "\uffffsubdir1" assert list_dir[0]["is_directory"] == True - assert list_dir[1]["name"] == "\uFFFFfile1" + assert list_dir[1]["name"] == "\ufffffile1" assert list_dir[1]["is_directory"] == False @FileSharePreparer() 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 e85c148fae68..e25c9fc3fabd 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 @@ -14,7 +14,6 @@ from azure.storage.fileshare import ShareClient, ShareDirectoryClient, ShareFileClient, ShareServiceClient from azure.storage.fileshare._shared.constants import X_MS_VERSION - # ------------------------------------------------------------------------------ TEST_FILE_PREFIX = "file" 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 b305398d93ab..bf8b13bab833 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 @@ -14,7 +14,6 @@ from azure.storage.fileshare._shared.constants import X_MS_VERSION from azure.storage.fileshare.aio import ShareClient, ShareDirectoryClient, ShareFileClient, ShareServiceClient - # ------------------------------------------------------------------------------ TEST_FILE_PREFIX = "file" 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 880a88d9b093..42667ce47aa5 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 @@ -23,7 +23,6 @@ from devtools_testutils.storage.testcase import generate_sas_token from settings.testcase import FileSharePreparer - # ------------------------------------------------------------------------------ SERVICES = { ShareServiceClient: "file", 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 a095e9c3dd39..5c8eed177a92 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 @@ -15,7 +15,6 @@ from devtools_testutils.storage.testcase import generate_sas_token from settings.testcase import FileSharePreparer - # ------------------------------------------------------------------------------ SERVICES = { ShareServiceClient: "file", 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 89b9a2f4c41a..70b7ce7a2b33 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 @@ -25,7 +25,6 @@ ) from azure.storage.fileshare.aio import ShareServiceClient - # ------------------------------------------------------------------------------ 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 a2feef539ef9..0a97ab973a88 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_handle.py +++ b/sdk/storage/azure-storage-file-share/tests/test_handle.py @@ -14,7 +14,6 @@ from azure.storage.fileshare import ShareServiceClient - # ------------------------------------------------------------------------------ TEST_SHARE_NAME = "test-share" # ------------------------------------------------------------------------------ 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 048f1edfe110..e374242c09a0 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 @@ -13,7 +13,6 @@ import pytest from azure.storage.fileshare.aio import ShareServiceClient - # ------------------------------------------------------------------------------ TEST_SHARE_NAME = "test-share" # ------------------------------------------------------------------------------ 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 be0067dcb8c6..e9fc041b7b47 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_nfs.py +++ b/sdk/storage/azure-storage-file-share/tests/test_nfs.py @@ -25,7 +25,6 @@ from devtools_testutils.storage import StorageRecordedTestCase from settings.testcase import FileSharePreparer - TEST_INTENT = "backup" TEST_FILE_PREFIX = "file" TEST_DIRECTORY_PREFIX = "directory" 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 961da25149ba..6568e0fe21d7 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 @@ -21,7 +21,6 @@ from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase from settings.testcase import FileSharePreparer - TEST_INTENT = "backup" TEST_FILE_PREFIX = "file" TEST_DIRECTORY_PREFIX = "directory" diff --git a/sdk/storage/azure-storage-file-share/tsp-location.yaml b/sdk/storage/azure-storage-file-share/tsp-location.yaml index 1a710edd36c7..2a735d219eae 100644 --- a/sdk/storage/azure-storage-file-share/tsp-location.yaml +++ b/sdk/storage/azure-storage-file-share/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/storage/data-plane/FileStorage -commit: -repo: +commit: cfd58963682948f5242b945bc6152c4e54c88c0c +repo: Azure/azure-rest-api-specs additionalDirectories: From 23cb05d3714c5e15e15381e55a66aa4e61066f61 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 20 May 2026 10:29:18 -0700 Subject: [PATCH 41/45] fixing up backcompat models for api parity --- .../fileshare/_generated/models/_patch.py | 297 ++++------------- .../azure/storage/fileshare/_models.py | 307 ++++++++++++++++-- 2 files changed, 338 insertions(+), 266 deletions(-) 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 a0cd1431e1bf..96282242bb3b 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 @@ -11,131 +11,27 @@ # TODO: Waiting for emitter release with perf improvements before editing the patch import xml.etree.ElementTree as ET -from typing import Any, Callable, List, Optional +from typing import Any, Callable, Dict, List, Optional -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 +from .._utils.model_base import Model as _deserialize +from azure.core.serialization import as_attribute_dict # --------------------------------------------------------------------------- -# 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 +# Backcompat shims for public methods that existed on the old autorest msrest models. +# 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. +# here preserves backward compatibility for users. # --------------------------------------------------------------------------- -_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( +def 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: +) -> Dict[str, Any]: """Backcompat wrapper that returns Python attribute names (snake_case). Accepts both the old autorest signature (``keep_readonly``, @@ -144,131 +40,68 @@ def _patched_as_dict( 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. -# --------------------------------------------------------------------------- + result = as_attribute_dict(self, exclude_readonly=not keep_readonly) + return result -def _asdict_value(v: Any) -> Any: - if v is None: +class _ModelBackCompatMixin: + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> Dict[str, Any]: + """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. + """ + return as_attribute_dict(self, exclude_readonly=not keep_readonly) + + @classmethod + def 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) + + @classmethod + def from_dict( + cls, + data: Any, + key_extractors: Optional[Callable[[str, dict[str, Any], 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) + + @classmethod + def 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 - 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 + @classmethod + def is_xml_model(cls) -> bool: + """Backcompat classmethod for the old autorest ``Model.is_xml_model``. -_Model._asdict = _patched_namedtuple_asdict + 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)) __all__: List[str] = [] 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 a8a7454c615c..18569b895224 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 @@ -7,6 +7,7 @@ # pylint: disable=too-few-public-methods, too-many-instance-attributes, super-init-not-called, too-many-lines from enum import Enum +import xml.etree.ElementTree as ET from typing import Any, Callable, Dict, List, Literal, Optional, Union, TYPE_CHECKING from urllib.parse import unquote from typing_extensions import Self @@ -16,6 +17,7 @@ from azure.core.paging import PageIterator from ._generated._utils.serialization import Deserializer +from ._generated.models._patch import _ModelBackCompatMixin, as_dict as _backcompat_as_dict from ._generated.models import AccessPolicy as GenAccessPolicy from ._generated.models import CorsRule as GeneratedCorsRule from ._generated.models import DirectoryItem @@ -42,7 +44,7 @@ def _wrap_item(item): return {"name": item.name, "size": item.properties.content_length, "is_directory": False} -class RetentionPolicy(GeneratedRetentionPolicy): +class RetentionPolicy(GeneratedRetentionPolicy, _ModelBackCompatMixin): """The retention policy which determines how long the associated data should persist. @@ -62,22 +64,46 @@ class RetentionPolicy(GeneratedRetentionPolicy): All data older than this value will be deleted.""" def __init__(self, enabled: bool = False, days: Optional[int] = None) -> None: - self.enabled = enabled - self.days = days - if self.enabled and (self.days is None): + if enabled and (days is None): raise ValueError("If policy is enabled, 'days' must be specified.") + super().__init__(enabled=enabled, days=days) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] @classmethod def _from_generated(cls, generated): if not generated: return cls() + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedRetentionPolicy(generated) # type: ignore[assignment,call-overload] return cls( enabled=generated.enabled, days=generated.days, ) -class Metrics(GeneratedMetrics): +class Metrics(GeneratedMetrics, _ModelBackCompatMixin): """A summary of request statistics grouped by API in hour or minute aggregates for files. @@ -103,15 +129,42 @@ 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() + super().__init__( + version=kwargs.get("version", "1.0"), + enabled=kwargs.get("enabled", False), + include_apis=kwargs.get("include_apis"), + retention_policy=kwargs.get("retention_policy") or RetentionPolicy(), + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] @classmethod def _from_generated(cls, generated): if not generated: return cls() + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedMetrics(generated) # type: ignore[assignment,call-overload] return cls( version=generated.version, enabled=generated.enabled, @@ -122,7 +175,7 @@ def _from_generated(cls, generated): ) -class CorsRule(GeneratedCorsRule): +class CorsRule(GeneratedCorsRule, _ModelBackCompatMixin): """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 @@ -168,11 +221,35 @@ 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) + super().__init__( + allowed_origins=",".join(allowed_origins), + allowed_methods=",".join(allowed_methods), + allowed_headers=",".join(kwargs.get("allowed_headers", [])), + exposed_headers=",".join(kwargs.get("exposed_headers", [])), + max_age_in_seconds=kwargs.get("max_age_in_seconds", 0), + ) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] @staticmethod def _to_generated(rules: Optional[List["CorsRule"]]) -> Optional[List[GeneratedCorsRule]]: @@ -194,6 +271,9 @@ def _to_generated(rules: Optional[List["CorsRule"]]) -> Optional[List[GeneratedC @classmethod def _from_generated(cls, generated): + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedCorsRule(generated) # type: ignore[assignment,call-overload] return cls( [generated.allowed_origins], [generated.allowed_methods], @@ -203,7 +283,7 @@ def _from_generated(cls, generated): ) -class SmbMultichannel(GeneratedSmbMultichannel): +class SmbMultichannel(GeneratedSmbMultichannel, _ModelBackCompatMixin): """Settings for Multichannel. :keyword bool enabled: If SMB Multichannel is enabled. @@ -213,10 +293,32 @@ class SmbMultichannel(GeneratedSmbMultichannel): """If SMB Multichannel is enabled.""" def __init__(self, *, enabled: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self.enabled = enabled + super().__init__(enabled=enabled) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] -class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): +class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit, _ModelBackCompatMixin): """Settings for encryption in transit. :keyword bool required: If encryption in transit is required. @@ -226,10 +328,32 @@ class SmbEncryptionInTransit(GeneratedSmbEncryptionInTransit): """If encryption in transit is enabled.""" def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self.required = required + super().__init__(required=required) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] -class ShareSmbSettings(GeneratedShareSmbSettings): +class ShareSmbSettings(GeneratedShareSmbSettings, _ModelBackCompatMixin): """Settings for the SMB protocol. :keyword SmbMultichannel multichannel: Sets the multichannel settings. @@ -248,13 +372,34 @@ def __init__( # pylint: disable=unused-argument encryption_in_transit: Optional[SmbEncryptionInTransit] = None, **kwargs: Any ) -> None: - self.multichannel = multichannel - self.encryption_in_transit = encryption_in_transit + super().__init__(multichannel=multichannel, encryption_in_transit=encryption_in_transit) if self.multichannel is None and self.encryption_in_transit is None: raise ValueError("The value 'multichannel' or 'encryption_in_transit' must be specified.") + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] + -class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): +class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit, _ModelBackCompatMixin): """Settings for encryption in transit. :keyword bool required: If encryption in transit is required. @@ -264,10 +409,32 @@ class NfsEncryptionInTransit(GeneratedNfsEncryptionInTransit): """If encryption in transit is enabled.""" def __init__(self, *, required: bool, **kwargs: Any) -> None: # pylint: disable=unused-argument - self.required = required + super().__init__(required=required) + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] -class ShareNfsSettings(GeneratedShareNfsSettings): + +class ShareNfsSettings(GeneratedShareNfsSettings, _ModelBackCompatMixin): """Settings for the NFS protocol. :keyword NfsEncryptionInTransit encryption_in_transit: Sets the encryption in transit settings. @@ -279,10 +446,32 @@ class ShareNfsSettings(GeneratedShareNfsSettings): def __init__( # pylint: disable=unused-argument self, *, encryption_in_transit: NfsEncryptionInTransit, **kwargs: Any ) -> None: - self.encryption_in_transit = encryption_in_transit + super().__init__(encryption_in_transit=encryption_in_transit) + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] -class ShareProtocolSettings(GeneratedShareProtocolSettings): +class ShareProtocolSettings(GeneratedShareProtocolSettings, _ModelBackCompatMixin): """Protocol Settings class used by the set and get service properties methods in the share service. Contains protocol properties of the share service such as the SMB and NFS setting of the share service. @@ -299,14 +488,38 @@ class ShareProtocolSettings(GeneratedShareProtocolSettings): def __init__( # pylint: disable=unused-argument self, *, smb: Optional[ShareSmbSettings] = None, nfs: Optional[ShareNfsSettings] = None, **kwargs: Any ) -> None: - self.smb = smb - self.nfs = nfs + super().__init__(smb=smb, nfs=nfs) if self.smb is None and self.nfs is None: raise ValueError("The value 'smb' or 'nfs' must be specified.") + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] + @classmethod def _from_generated(cls, generated): - return cls(smb=generated.smb, nfs=generated.nfs) + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedShareProtocolSettings(generated) # type: ignore[assignment,call-overload] + return cls(smb=generated.smb, nfs=generated.nfs) # type: ignore[arg-type] class ShareSasPermissions: @@ -386,7 +599,7 @@ def from_string(cls, permission: str) -> Self: return parsed -class AccessPolicy(GenAccessPolicy): +class AccessPolicy(GenAccessPolicy, _ModelBackCompatMixin): """Access Policy class used by the set and get acl methods in each service. A stored access policy can specify the start time, expiry time, and @@ -444,9 +657,32 @@ def __init__( expiry: Optional[Union["datetime", str]] = None, start: Optional[Union["datetime", str]] = None, ) -> None: - self.start = start - self.expiry = expiry - self.permission = permission + super().__init__() + self.start = start # type: ignore [assignment] + self.expiry = expiry # type: ignore [assignment] + self.permission = permission # type: ignore [assignment] + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + **kwargs: Any, + ) -> Dict[str, Any]: + """Return a dict representation of the model. + + :param bool keep_readonly: Whether to include readonly fields. + :param key_transformer: A callable to transform each key serialized + from the model. + :type key_transformer: Optional[Callable[[str, Dict[str, Any], Any], Any]] + :return: A dictionary representation of this model. + :rtype: Dict[str, Any] + """ + return _backcompat_as_dict( + self, + keep_readonly=keep_readonly, + key_transformer=key_transformer, + **kwargs, + ) # type: ignore[return-value] class LeaseProperties(DictMixin): @@ -1380,6 +1616,9 @@ def from_string(cls, permission: str) -> Self: def service_properties_deserialize(generated: GeneratedStorageServiceProperties) -> Dict[str, Any]: + # Handle XML Element by converting to generated model first + if isinstance(generated, ET.Element): + generated = GeneratedStorageServiceProperties(generated) # type: ignore[assignment,call-overload] 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 From 9bac73254591d48fc101979f881671c9e8319d97 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Wed, 20 May 2026 15:14:34 -0700 Subject: [PATCH 42/45] update wrapper for iter_bytes --- .../azure/storage/fileshare/_shared/policies.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) 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 b5d0b7d79766..113b241c1b84 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 @@ -468,16 +468,20 @@ def _validate_content_response( content_length = int(response.http_response.headers[CONTENT_LENGTH_HEADER]) # Patch response to return response iterator wrapped in structured message decoder - original_stream_download = response.http_response.stream_download + original_iter_bytes = response.http_response.iter_bytes - def wrapped_stream_download(*args, **kwargs): - iterator = original_stream_download(*args, **kwargs) + + def wrapped_iter_bytes(*args, **kwargs): + iterator = original_iter_bytes(*args, **kwargs) decoder = decoder_cls(iterator, content_length, block_size=DATA_BLOCK_SIZE) - decoder.request = iterator.request # type: ignore - decoder.response = iterator.response # type: ignore + # Only set request/response if present on iterator + if hasattr(iterator, 'request'): + decoder.request = iterator.request # type: ignore + if hasattr(iterator, 'response'): + decoder.response = iterator.response # type: ignore return decoder - response.http_response.stream_download = wrapped_stream_download + response.http_response.iter_bytes = wrapped_iter_bytes class StorageContentValidation(SansIOHTTPPolicy): From 0bdd56ba33956a7f8c348fd5b5487002f0c4bbf0 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Thu, 21 May 2026 09:04:09 -0700 Subject: [PATCH 43/45] tests/samples w/o formatting changes --- .../azure-storage-file-share/CHANGELOG.md | 3 + .../samples/file_samples_authentication.py | 74 +- .../file_samples_authentication_async.py | 75 +- .../samples/file_samples_client.py | 28 +- .../samples/file_samples_client_async.py | 24 +- .../samples/file_samples_directory.py | 28 +- .../samples/file_samples_directory_async.py | 29 +- .../samples/file_samples_hello_world.py | 32 +- .../samples/file_samples_hello_world_async.py | 38 +- .../samples/file_samples_service.py | 38 +- .../samples/file_samples_service_async.py | 45 +- .../samples/file_samples_share.py | 52 +- .../samples/file_samples_share_async.py | 47 +- .../tests/encryption_test_helper.py | 45 +- .../T1_legacy_tests/_test_base.py | 43 +- .../T1_legacy_tests/download.py | 9 +- .../T1_legacy_tests/download_to_file.py | 9 +- .../T1_legacy_tests/upload.py | 3 +- .../T1_legacy_tests/upload_from_file.py | 3 +- .../tests/perfstress_tests/_test_base.py | 46 +- .../tests/perfstress_tests/upload.py | 10 +- .../perfstress_tests/upload_from_file.py | 4 +- .../tests/settings/settings_fake.py | 2 +- .../tests/settings/testcase.py | 56 +- .../tests/test_directory.py | 543 ++++--- .../tests/test_directory_async.py | 571 ++++--- .../tests/test_file.py | 1237 +++++++--------- .../tests/test_file_api_version.py | 80 +- .../tests/test_file_api_version_async.py | 80 +- .../tests/test_file_async.py | 1317 ++++++++--------- .../tests/test_file_client.py | 324 ++-- .../tests/test_file_client_async.py | 309 ++-- .../tests/test_file_service_properties.py | 72 +- .../test_file_service_properties_async.py | 48 +- .../tests/test_get_file.py | 543 ++++--- .../tests/test_get_file_async.py | 531 ++++--- .../tests/test_handle.py | 36 +- .../tests/test_handle_async.py | 25 +- .../tests/test_helpers.py | 138 +- .../tests/test_helpers_async.py | 148 +- .../tests/test_nfs.py | 186 +-- .../tests/test_nfs_async.py | 190 +-- .../tests/test_share.py | 475 +++--- .../tests/test_share_async.py | 479 +++--- 44 files changed, 3844 insertions(+), 4231 deletions(-) diff --git a/sdk/storage/azure-storage-file-share/CHANGELOG.md b/sdk/storage/azure-storage-file-share/CHANGELOG.md index 162222511349..ada28a578d11 100644 --- a/sdk/storage/azure-storage-file-share/CHANGELOG.md +++ b/sdk/storage/azure-storage-file-share/CHANGELOG.md @@ -4,6 +4,9 @@ ### Features Added +### Other Changes +- Legacy transports will not be supported moving forward + ## 12.25.0 (2026-05-14) ### Features Added 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 72ca101ceb5b..b7207e0608da 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,7 +32,6 @@ 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") @@ -43,73 +42,55 @@ 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 @@ -120,17 +101,14 @@ 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] @@ -138,34 +116,32 @@ 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 021cff228797..37cfb1546302 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,7 +33,6 @@ 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") @@ -44,72 +43,54 @@ 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 @@ -120,16 +101,13 @@ 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] @@ -137,27 +115,25 @@ 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] @@ -170,6 +146,5 @@ 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 8da3dda6d560..0e0f967c8db3 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,16 +36,12 @@ 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 @@ -86,14 +82,12 @@ 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 @@ -110,7 +104,9 @@ 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 @@ -123,14 +119,12 @@ 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 @@ -143,7 +137,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] @@ -153,7 +147,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 54099136a919..6b78b23818ea 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 @@ -21,6 +21,7 @@ 2) STORAGE_ACCOUNT_NAME - the name of the storage account """ + import asyncio import os import sys @@ -37,16 +38,12 @@ 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 @@ -88,16 +85,12 @@ 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 @@ -115,7 +108,9 @@ 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 @@ -132,6 +127,5 @@ 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 05e64639acd2..756218476608 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,20 +30,16 @@ 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 @@ -78,16 +74,12 @@ 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 @@ -131,16 +123,12 @@ 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 @@ -161,7 +149,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 989f7a06761e..7455d243f40e 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,20 +31,16 @@ 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 @@ -80,16 +76,12 @@ 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 @@ -136,16 +128,12 @@ 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 @@ -173,6 +161,5 @@ 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 2c5cb80accb5..c8835ddf4a25 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,32 +30,26 @@ 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 @@ -72,16 +66,12 @@ 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 @@ -91,10 +81,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 @@ -106,7 +96,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 41ebb787fa96..7da6919838b9 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,34 +31,27 @@ 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 @@ -76,17 +69,13 @@ 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: @@ -96,10 +85,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 @@ -118,6 +107,5 @@ 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 1675db6bb42c..0bb0e5c95961 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,20 +31,16 @@ 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] @@ -53,14 +49,13 @@ 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"] @@ -69,8 +64,7 @@ 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] @@ -84,16 +78,12 @@ 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] @@ -116,12 +106,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 @@ -129,7 +119,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 2c1d155577d2..1658aa158b23 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,20 +32,16 @@ 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] @@ -54,14 +50,13 @@ 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"] @@ -70,15 +65,14 @@ 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() @@ -86,16 +80,12 @@ 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: @@ -121,16 +111,12 @@ 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 @@ -144,6 +130,5 @@ 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 5beb9a3fb812..21547765cef6 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,20 +33,16 @@ 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] @@ -64,16 +60,12 @@ 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] @@ -87,7 +79,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] @@ -100,15 +92,11 @@ 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") @@ -139,16 +127,12 @@ 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 @@ -173,16 +157,12 @@ 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 @@ -193,14 +173,12 @@ 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 @@ -214,7 +192,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 5a8fd8d4cf0f..93aef67615bf 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,20 +34,16 @@ 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: @@ -66,16 +62,12 @@ 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] @@ -90,7 +82,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] @@ -103,15 +95,11 @@ 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") @@ -145,16 +133,12 @@ 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 @@ -182,16 +166,12 @@ 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 @@ -209,6 +189,5 @@ 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/tests/encryption_test_helper.py b/sdk/storage/azure-storage-file-share/tests/encryption_test_helper.py index f0144365c315..3c25756940cb 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 @@ -16,30 +16,31 @@ aes_key_unwrap, ) + _ERROR_UNKNOWN_KEY_WRAP_ALGORITHM = "Unknown keywrap algorithm specified. Supported algorithm: A256KW." 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 @@ -57,29 +58,37 @@ 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()), algorithm=SHA1(), label=None) # nosec # nosec - ) + 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) + ) 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()), algorithm=SHA1(), label=None) # nosec # nosec - ) + if algorithm == 'RSA': + return self.private_key.decrypt(key, + OAEP( + mgf=MGF1(algorithm=SHA1()), # nosec + algorithm=SHA1(), # nosec + label=None) + ) 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 e707bd60e59f..0b248d5801ef 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,20 +3,18 @@ # 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 - +from azure.storage.file import FileService # pylint: disable=no-name-in-module class _LegacyServiceTest(PerfStressTest): service_client = None async_service_client = None def __init__(self, arguments): - super().__init__(arguments) + super().__init__(arguments) # pylint: disable=useless-parent-delegation 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) @@ -29,36 +27,41 @@ 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): + def __init__(self, arguments): # pylint: disable=useless-parent-delegation 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 2783dc073d99..1655d95cd073 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,8 +18,10 @@ 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() @@ -28,8 +30,7 @@ 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 15dd8242a500..08719e5515dc 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,8 +19,10 @@ 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() @@ -36,8 +38,7 @@ 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 6d6d21fe62e7..077f2fb7abf0 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,8 +24,7 @@ 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 fb73f2cafcc7..46b121963b75 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,8 +36,7 @@ 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 c609f58b8eab..a19693235876 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,7 +3,6 @@ # 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 @@ -21,16 +20,18 @@ 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() @@ -40,29 +41,34 @@ 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 2efe6d1de3f0..7380b321a064 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,11 +18,13 @@ 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 781543fcd79e..e113cc804436 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 bbd8f1db9757..84dcade5460f 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 99aab3531ddc..c0465c4a67ed 100644 --- a/sdk/storage/azure-storage-file-share/tests/settings/testcase.py +++ b/sdk/storage/azure-storage-file-share/tests/settings/testcase.py @@ -4,25 +4,16 @@ # 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 * @@ -30,37 +21,27 @@ # 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 -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 +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", @@ -76,5 +57,4 @@ 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 2c4ed50a0530..72ad5cc0030c 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_directory.py +++ b/sdk/storage/azure-storage-file-share/tests/test_directory.py @@ -1,4 +1,3 @@ -# 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,9 +8,13 @@ from datetime import datetime, timedelta, timezone import pytest -from azure.core.exceptions import ClientAuthenticationError, ResourceExistsError, ResourceNotFoundError + +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.storage.fileshare import ( - ContentSettings, generate_share_sas, NTFSAttributes, ShareDirectoryClient, @@ -20,16 +23,11 @@ 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" @@ -38,7 +36,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: @@ -52,7 +50,6 @@ def _teardown(self, FILE_PATH): os.remove(FILE_PATH) except: pass - # --Helpers----------------------------------------------------------------- # --Test cases for directories ---------------------------------------------- @@ -66,7 +63,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 @@ -79,10 +76,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 @@ -98,9 +95,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 @@ -114,19 +111,17 @@ 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 @@ -134,8 +129,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 @@ -148,12 +143,10 @@ 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() @@ -169,22 +162,20 @@ 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 @@ -194,14 +185,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 @@ -211,15 +202,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 @@ -231,19 +222,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 @@ -252,10 +243,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) @@ -271,9 +262,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 @@ -292,7 +283,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") @@ -307,15 +298,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() @@ -327,7 +318,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() @@ -348,12 +339,10 @@ 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() @@ -373,14 +362,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 @@ -398,12 +387,10 @@ 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() @@ -423,14 +410,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 @@ -445,7 +432,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): @@ -461,7 +448,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() @@ -477,7 +464,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): @@ -493,7 +480,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: @@ -510,13 +497,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 @@ -531,11 +518,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() @@ -550,8 +537,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) @@ -570,13 +557,11 @@ 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() @@ -594,7 +579,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 @@ -618,12 +603,10 @@ 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() @@ -638,10 +621,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() @@ -659,7 +642,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 @@ -673,12 +656,11 @@ 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 @@ -696,12 +678,10 @@ 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() @@ -716,12 +696,11 @@ 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 @@ -738,7 +717,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") @@ -751,18 +730,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 @@ -775,12 +754,10 @@ 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() @@ -796,18 +773,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 @@ -818,12 +795,10 @@ 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.") @@ -833,12 +808,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 @@ -848,19 +823,19 @@ 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.create_subdirectory("subdir1\ufffe") - directory.upload_file("file\ufffe", "data1") + directory = share_client.create_directory('directory\uFFFE') + directory.create_subdirectory("subdir1\uFFFE") + directory.upload_file("file\uFFFE", "data1") # Act list_dir = list(directory.list_directories_and_files()) # 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 @@ -870,19 +845,19 @@ 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.create_subdirectory("\uffffsubdir1") - directory.upload_file("\ufffffile", "data1") + directory = share_client.create_directory('\uFFFFdirectory') + directory.create_subdirectory("\uFFFFsubdir1") + directory.upload_file("\uFFFFfile", "data1") # Act - list_dir = list(directory.list_directories_and_files(name_starts_with="\uffff")) + list_dir = list(directory.list_directories_and_files(name_starts_with="\uFFFF")) # 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 @@ -892,7 +867,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") @@ -901,9 +876,8 @@ 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 @@ -926,7 +900,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)) @@ -943,7 +917,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") @@ -956,12 +930,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 @@ -971,7 +945,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") @@ -982,20 +956,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 @@ -1005,7 +979,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") @@ -1018,11 +992,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 @@ -1039,11 +1013,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}" @@ -1056,7 +1030,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() @@ -1077,12 +1051,10 @@ 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() @@ -1103,12 +1075,10 @@ 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() @@ -1127,7 +1097,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): @@ -1143,7 +1113,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() @@ -1163,10 +1133,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() @@ -1183,16 +1153,14 @@ 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() @@ -1207,13 +1175,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 @@ -1229,17 +1197,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() @@ -1256,10 +1224,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() @@ -1275,12 +1243,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() @@ -1296,7 +1264,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) @@ -1305,18 +1273,17 @@ 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), props.file_attributes.replace(" " == "") + assert str(file_attributes).replace(' ', '') == 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 @@ -1330,15 +1297,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() @@ -1360,16 +1327,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() @@ -1383,16 +1350,14 @@ 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() @@ -1411,22 +1376,20 @@ 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 @@ -1443,22 +1406,20 @@ 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=f"https://badaudience.file.core.windows.net", + audience='https://badaudience.file.core.windows.net' ) # Assert @@ -1472,45 +1433,50 @@ 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 @@ -1525,21 +1491,20 @@ 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 a1fef26ce12a..70397a88c842 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,4 +1,3 @@ -# pylint: disable=too-many-lines # coding: utf-8 # ------------------------------------------------------------------------- @@ -8,24 +7,28 @@ # -------------------------------------------------------------------------- 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 -# ------------------------------------------------------------------------------ -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)" +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_INTENT = "backup" @@ -35,7 +38,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) @@ -61,7 +64,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 @@ -75,10 +78,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() @@ -95,9 +98,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 @@ -112,19 +115,17 @@ 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 @@ -132,8 +133,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 @@ -147,12 +148,10 @@ 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() @@ -169,22 +168,20 @@ 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 @@ -195,14 +192,15 @@ 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 @@ -213,15 +211,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 @@ -233,11 +231,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 = [] @@ -246,8 +244,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 @@ -257,10 +255,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) @@ -278,9 +276,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 @@ -300,15 +298,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() @@ -321,7 +319,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() @@ -343,12 +341,10 @@ 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() @@ -369,14 +365,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 @@ -395,12 +391,10 @@ 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() @@ -421,14 +415,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 @@ -444,7 +438,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): @@ -460,7 +454,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") @@ -478,7 +472,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() @@ -495,7 +489,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): @@ -512,7 +506,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: @@ -530,13 +524,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 @@ -552,11 +546,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() @@ -572,8 +566,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) @@ -593,13 +587,11 @@ 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() @@ -618,7 +610,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 @@ -642,12 +634,10 @@ 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() @@ -662,10 +652,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() @@ -684,7 +674,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 @@ -698,12 +688,11 @@ 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 @@ -721,12 +710,10 @@ 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() @@ -741,12 +728,11 @@ 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 @@ -763,15 +749,14 @@ 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 = [] @@ -781,21 +766,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 @@ -809,12 +794,10 @@ 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() @@ -824,8 +807,7 @@ 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 = [] @@ -835,21 +817,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 @@ -861,17 +843,15 @@ 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 @@ -881,12 +861,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 @@ -897,10 +877,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 = [] @@ -909,10 +889,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 @@ -923,22 +903,22 @@ 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 = [] - async for d in directory.list_directories_and_files(name_starts_with="\uffff"): + async for d in directory.list_directories_and_files(name_starts_with="\uFFFF"): list_dir.append(d) # 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 @@ -949,15 +929,14 @@ 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 = [] @@ -989,8 +968,9 @@ 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 = [] @@ -1011,15 +991,14 @@ 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 = [] @@ -1028,12 +1007,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 @@ -1044,22 +1023,20 @@ 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 = [] @@ -1068,13 +1045,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 @@ -1085,15 +1062,14 @@ 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 = [] @@ -1102,11 +1078,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 @@ -1125,7 +1101,9 @@ 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 @@ -1141,7 +1119,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() @@ -1163,12 +1141,10 @@ 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() @@ -1190,12 +1166,10 @@ 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() @@ -1215,7 +1189,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): @@ -1232,7 +1206,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() @@ -1253,10 +1227,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() @@ -1274,16 +1248,14 @@ 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() @@ -1299,13 +1271,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 @@ -1322,17 +1294,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() @@ -1350,10 +1322,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() @@ -1370,12 +1342,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() @@ -1392,7 +1364,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) @@ -1401,18 +1373,17 @@ 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 @@ -1427,15 +1398,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() @@ -1458,16 +1429,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() @@ -1482,16 +1453,14 @@ 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() @@ -1510,22 +1479,20 @@ 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 @@ -1542,22 +1509,20 @@ 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=f"https://badaudience.file.core.windows.net", + audience='https://badaudience.file.core.windows.net' ) # Assert @@ -1571,19 +1536,17 @@ 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() @@ -1591,7 +1554,8 @@ 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() @@ -1599,19 +1563,23 @@ 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 @@ -1626,19 +1594,18 @@ 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 a046a1d8f1f6..03a5a449fae5 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_file.py +++ b/sdk/storage/azure-storage-file-share/tests/test_file.py @@ -1,4 +1,3 @@ -# 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 @@ -10,14 +9,15 @@ 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 ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, -) +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError from azure.storage.blob import BlobServiceClient from azure.storage.fileshare import ( AccessPolicy, @@ -35,22 +35,16 @@ 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" # ------------------------------------------------------------------------------ @@ -67,8 +61,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) @@ -102,7 +96,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): @@ -119,7 +113,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() @@ -129,7 +123,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) @@ -141,13 +135,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() @@ -179,7 +173,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 @@ -195,7 +189,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 @@ -204,7 +198,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") @@ -213,7 +207,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 @@ -223,19 +217,20 @@ 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 @@ -249,8 +244,7 @@ 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() @@ -270,8 +264,7 @@ 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") @@ -282,8 +275,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 @@ -299,8 +292,7 @@ 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) @@ -311,8 +303,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 @@ -344,10 +336,9 @@ 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) @@ -358,9 +349,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 @@ -373,10 +364,9 @@ 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) @@ -385,10 +375,9 @@ 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( @@ -396,18 +385,17 @@ 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 @@ -418,14 +406,13 @@ 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) @@ -433,8 +420,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() @@ -444,15 +431,14 @@ 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) @@ -460,10 +446,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 @@ -489,45 +475,6 @@ 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): @@ -538,7 +485,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 @@ -563,11 +510,10 @@ 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 @@ -588,9 +534,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): @@ -615,13 +561,12 @@ 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): @@ -643,15 +588,14 @@ 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): @@ -669,7 +613,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 @@ -702,8 +646,7 @@ 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( @@ -711,8 +654,7 @@ 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 @@ -720,8 +662,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 @@ -750,8 +692,7 @@ 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): @@ -777,8 +718,7 @@ 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 @@ -829,8 +769,7 @@ 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): @@ -860,7 +799,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): @@ -881,7 +820,9 @@ 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 @@ -915,10 +856,14 @@ 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() @@ -932,14 +877,15 @@ 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 @@ -949,7 +895,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 @@ -961,7 +907,9 @@ 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) @@ -974,7 +922,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 @@ -1001,12 +949,11 @@ 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 @@ -1047,8 +994,7 @@ 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) @@ -1069,10 +1015,9 @@ 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 @@ -1080,8 +1025,7 @@ 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() @@ -1099,11 +1043,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() @@ -1135,8 +1079,7 @@ 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 @@ -1163,8 +1106,7 @@ 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) @@ -1189,8 +1131,7 @@ 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): @@ -1221,7 +1162,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 @@ -1230,10 +1171,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 @@ -1249,9 +1190,8 @@ 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) @@ -1260,10 +1200,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 @@ -1273,7 +1213,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 @@ -1287,10 +1227,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) @@ -1298,12 +1238,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) @@ -1312,10 +1252,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 @@ -1347,8 +1287,7 @@ 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) @@ -1369,10 +1308,9 @@ 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 @@ -1394,8 +1332,7 @@ 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): @@ -1413,7 +1350,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 @@ -1433,14 +1370,13 @@ 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() @@ -1449,7 +1385,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 @@ -1459,10 +1395,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) @@ -1484,7 +1420,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 @@ -1500,14 +1436,13 @@ 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() @@ -1521,7 +1456,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 @@ -1539,7 +1474,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 @@ -1553,10 +1488,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 @@ -1567,10 +1502,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): @@ -1584,12 +1519,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 @@ -1600,27 +1535,21 @@ 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() @@ -1631,18 +1560,16 @@ 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 @@ -1651,14 +1578,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( @@ -1668,38 +1595,27 @@ 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() @@ -1709,14 +1625,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 @@ -1727,21 +1643,20 @@ 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() @@ -1751,11 +1666,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 @@ -1766,15 +1681,13 @@ 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 @@ -1787,11 +1700,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 @@ -1802,15 +1715,13 @@ 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 @@ -1830,7 +1741,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() @@ -1844,10 +1755,9 @@ 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 @@ -1856,9 +1766,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 @@ -1870,10 +1780,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() @@ -1894,8 +1804,7 @@ 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 @@ -1916,10 +1825,9 @@ 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 @@ -1929,7 +1837,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 @@ -1943,15 +1851,14 @@ 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() @@ -1972,8 +1879,7 @@ 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) @@ -1985,7 +1891,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 @@ -1993,20 +1899,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 @@ -2022,8 +1928,7 @@ 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) @@ -2035,7 +1940,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 @@ -2043,20 +1948,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 @@ -2069,10 +1974,9 @@ 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) @@ -2084,7 +1988,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 @@ -2093,22 +1997,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 @@ -2122,8 +2026,7 @@ 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) @@ -2134,7 +2037,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): @@ -2147,8 +2050,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 @@ -2162,11 +2065,10 @@ 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) @@ -2176,10 +2078,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 @@ -2193,8 +2095,7 @@ 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) @@ -2204,8 +2105,7 @@ 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() @@ -2230,8 +2130,7 @@ 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) @@ -2242,8 +2141,7 @@ 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() @@ -2266,10 +2164,9 @@ 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) @@ -2280,8 +2177,7 @@ 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() @@ -2291,10 +2187,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 @@ -2307,17 +2203,16 @@ 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 @@ -2334,18 +2229,17 @@ 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 @@ -2361,28 +2255,26 @@ 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 @@ -2398,11 +2290,10 @@ 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): @@ -2412,8 +2303,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 @@ -2429,9 +2320,8 @@ 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) @@ -2444,8 +2334,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 @@ -2461,9 +2351,8 @@ 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) @@ -2485,15 +2374,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 @@ -2511,21 +2400,23 @@ 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 @@ -2542,19 +2433,18 @@ 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) @@ -2572,9 +2462,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( @@ -2586,20 +2476,19 @@ 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() @@ -2617,9 +2506,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( @@ -2631,24 +2520,23 @@ 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() @@ -2659,13 +2547,9 @@ 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( @@ -2677,25 +2561,24 @@ 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 @@ -2707,20 +2590,19 @@ 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 @@ -2729,20 +2611,19 @@ 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 @@ -2751,29 +2632,28 @@ 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 @@ -2787,11 +2667,10 @@ 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 @@ -2808,14 +2687,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 @@ -2824,7 +2703,22 @@ 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+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==" + 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==' + ) binary_data = base64.b64decode(base64_data) file_name = self._get_file_reference() @@ -2832,8 +2726,7 @@ 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 @@ -2856,22 +2749,20 @@ 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) @@ -2891,14 +2782,13 @@ 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:]) @@ -2919,17 +2809,16 @@ 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() @@ -2945,8 +2834,7 @@ 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: @@ -2954,8 +2842,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) @@ -2974,15 +2862,13 @@ 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)) @@ -2991,8 +2877,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) @@ -3012,8 +2898,7 @@ 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) @@ -3022,8 +2907,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]) @@ -3042,8 +2927,7 @@ 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) @@ -3070,15 +2954,13 @@ 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)) @@ -3106,8 +2988,7 @@ 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 @@ -3133,15 +3014,13 @@ 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)) @@ -3163,15 +3042,14 @@ 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) @@ -3187,18 +3065,17 @@ 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) @@ -3212,14 +3089,13 @@ 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) @@ -3241,8 +3117,7 @@ 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) @@ -3263,8 +3138,7 @@ 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) @@ -3285,10 +3159,9 @@ 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 @@ -3312,10 +3185,9 @@ 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 @@ -3348,8 +3220,7 @@ 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 @@ -3360,19 +3231,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( @@ -3381,11 +3252,12 @@ 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() @@ -3416,10 +3288,9 @@ 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) + response = requests.get(file_client.url, timeout=15) # Assert assert response.ok @@ -3447,8 +3318,7 @@ 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() @@ -3461,6 +3331,7 @@ 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) @@ -3470,8 +3341,7 @@ 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() @@ -3487,8 +3357,7 @@ 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() @@ -3513,9 +3382,8 @@ 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) + credential=token) + response = requests.get(file_client.url, timeout=15) # Assert assert response.ok @@ -3537,11 +3405,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 @@ -3549,17 +3417,16 @@ 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) + credential=token) + response = requests.get(file_client.url, timeout=15) # 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() @@ -3568,7 +3435,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, @@ -3583,17 +3450,16 @@ 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) + 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) # 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() @@ -3616,11 +3482,10 @@ 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) + response = requests.delete(file_client.url, timeout=15) # Assert assert response.ok @@ -3634,13 +3499,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 @@ -3658,15 +3523,14 @@ 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 @@ -3679,15 +3543,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 @@ -3700,9 +3564,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) @@ -3711,7 +3575,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 @@ -3725,11 +3589,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() @@ -3745,14 +3609,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() @@ -3766,7 +3630,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) @@ -3775,17 +3639,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), props.file_attributes.replace(" " == "") + assert str(file_attributes).replace(' ', '') == 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 @@ -3797,11 +3661,13 @@ 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() @@ -3816,18 +3682,20 @@ 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 @@ -3846,19 +3714,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 @@ -3875,7 +3743,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) @@ -3890,7 +3758,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 @@ -3910,7 +3778,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) @@ -3925,7 +3793,7 @@ def test_bad_audience_file_client(self, **kwargs): file_path=file_name, credential=token_credential, token_intent=TEST_INTENT, - audience=f"https://badaudience.file.core.windows.net", + audience='https://badaudience.file.core.windows.net' ) # Assert @@ -3939,20 +3807,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 @@ -3960,23 +3828,29 @@ 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 @@ -3985,7 +3859,8 @@ 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 @@ -3993,19 +3868,22 @@ 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() + @pytest.mark.skip("Legacy transports will not be supported moving forward") @FileSharePreparer() def test_legacy_transport(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") @@ -4020,7 +3898,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() @@ -4036,6 +3914,7 @@ def test_legacy_transport(self, **kwargs): file_data = file_client.download_file().readall() assert file_data == b"Hello World!" # data is fixed by mock transport + @pytest.mark.skip("Legacy transports will not be supported moving forward") @FileSharePreparer() def test_legacy_transport_with_content_validation(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") @@ -4050,7 +3929,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!" @@ -4069,12 +3948,17 @@ 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" @@ -4094,11 +3978,12 @@ 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\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' + b'\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) @@ -4121,8 +4006,9 @@ 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\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' + b'\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) @@ -4143,8 +4029,7 @@ 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" @@ -4166,8 +4051,7 @@ 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) @@ -4191,7 +4075,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() @@ -4201,7 +4085,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() @@ -4211,7 +4095,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() @@ -4229,7 +4113,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 @@ -4237,5 +4121,4 @@ 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 e25c9fc3fabd..6d450be22723 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 @@ -14,8 +14,9 @@ from azure.storage.fileshare import ShareClient, ShareDirectoryClient, ShareFileClient, ShareServiceClient from azure.storage.fileshare._shared.constants import X_MS_VERSION + # ------------------------------------------------------------------------------ -TEST_FILE_PREFIX = "file" +TEST_FILE_PREFIX = 'file' class TestStorageClient(StorageRecordedTestCase): @@ -30,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() @@ -45,11 +46,14 @@ 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 @@ -57,8 +61,9 @@ 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 @@ -68,7 +73,10 @@ 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 @@ -76,8 +84,7 @@ 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 @@ -92,8 +99,10 @@ 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 @@ -102,8 +111,7 @@ 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 @@ -118,8 +126,10 @@ 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 @@ -128,21 +138,25 @@ 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: @@ -151,8 +165,7 @@ 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: @@ -161,8 +174,7 @@ 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() @@ -176,7 +188,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() @@ -184,20 +196,19 @@ 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) @@ -205,14 +216,13 @@ 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 bf8b13bab833..064591eb7e05 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 @@ -14,8 +14,9 @@ from azure.storage.fileshare._shared.constants import X_MS_VERSION from azure.storage.fileshare.aio import ShareClient, ShareDirectoryClient, ShareFileClient, ShareServiceClient + # ------------------------------------------------------------------------------ -TEST_FILE_PREFIX = "file" +TEST_FILE_PREFIX = 'file' class TestAsyncStorageClient(AsyncStorageRecordedTestCase): @@ -30,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() @@ -45,11 +46,14 @@ 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 @@ -57,8 +61,9 @@ 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 @@ -68,7 +73,10 @@ 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 @@ -76,8 +84,7 @@ 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 @@ -92,8 +99,10 @@ 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 @@ -102,8 +111,7 @@ 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 @@ -118,8 +126,10 @@ 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 @@ -128,21 +138,25 @@ 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: @@ -151,8 +165,7 @@ 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: @@ -161,8 +174,7 @@ 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() @@ -177,7 +189,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() @@ -185,20 +197,19 @@ 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) @@ -206,14 +217,13 @@ 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 b30bca211c6d..a739b1c53b87 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,4 +1,3 @@ -# 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 @@ -12,13 +11,14 @@ 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 ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, -) +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError from azure.storage.blob.aio import BlobServiceClient from azure.storage.fileshare import ( AccessPolicy, @@ -35,22 +35,16 @@ ) 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" # ------------------------------------------------------------------------------ @@ -64,10 +58,11 @@ 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") @@ -93,16 +88,15 @@ 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) @@ -133,7 +127,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() @@ -143,7 +137,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) @@ -155,13 +149,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) @@ -194,7 +188,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 @@ -210,7 +204,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 @@ -219,7 +213,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") @@ -228,7 +222,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 @@ -238,19 +232,20 @@ 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 @@ -265,8 +260,7 @@ 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() @@ -287,8 +281,7 @@ 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) @@ -296,8 +289,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 @@ -310,20 +303,19 @@ 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 @@ -342,7 +334,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() @@ -355,21 +347,20 @@ 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 @@ -383,10 +374,9 @@ 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) @@ -395,10 +385,9 @@ 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( @@ -406,18 +395,17 @@ 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 @@ -429,14 +417,13 @@ 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) @@ -444,8 +431,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() @@ -456,25 +443,24 @@ 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 @@ -500,46 +486,6 @@ 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): @@ -550,7 +496,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 @@ -576,11 +522,10 @@ 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 @@ -601,9 +546,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): @@ -629,13 +574,12 @@ 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): @@ -658,15 +602,14 @@ 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): @@ -684,7 +627,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 @@ -717,8 +660,7 @@ 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( @@ -726,8 +668,7 @@ 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 @@ -735,8 +676,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 @@ -792,8 +733,7 @@ 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): @@ -817,8 +757,7 @@ 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 @@ -843,8 +782,7 @@ 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): @@ -874,7 +812,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): @@ -895,7 +833,9 @@ 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 @@ -929,10 +869,14 @@ 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() @@ -945,16 +889,17 @@ 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 @@ -964,7 +909,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 @@ -976,7 +921,9 @@ 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) @@ -989,7 +936,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 @@ -1013,15 +960,14 @@ 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 @@ -1059,12 +1005,11 @@ 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) @@ -1086,10 +1031,9 @@ 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 @@ -1097,8 +1041,7 @@ 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() @@ -1116,11 +1059,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() @@ -1153,8 +1096,7 @@ 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 @@ -1180,8 +1122,7 @@ 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) @@ -1206,8 +1147,7 @@ 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): @@ -1238,7 +1178,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 @@ -1248,10 +1188,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 @@ -1264,13 +1204,12 @@ 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) @@ -1280,10 +1219,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 @@ -1293,7 +1232,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 @@ -1307,10 +1246,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) @@ -1319,11 +1258,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) @@ -1332,10 +1271,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 @@ -1368,8 +1307,7 @@ 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) @@ -1391,10 +1329,9 @@ 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 @@ -1416,8 +1353,7 @@ 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): @@ -1435,7 +1371,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 @@ -1456,14 +1392,13 @@ 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 @@ -1484,14 +1419,13 @@ 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() @@ -1500,7 +1434,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 @@ -1510,10 +1444,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) @@ -1534,7 +1468,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 @@ -1550,7 +1484,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 @@ -1568,7 +1502,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 @@ -1582,14 +1516,18 @@ 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 @@ -1600,10 +1538,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): @@ -1617,16 +1555,20 @@ 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 @@ -1637,10 +1579,9 @@ 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) @@ -1650,8 +1591,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() @@ -1663,22 +1604,18 @@ 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 @@ -1687,18 +1624,22 @@ 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( @@ -1708,16 +1649,14 @@ 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 @@ -1725,8 +1664,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() @@ -1736,18 +1675,24 @@ 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 @@ -1758,13 +1703,12 @@ 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 @@ -1772,8 +1716,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() @@ -1783,13 +1727,14 @@ 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 @@ -1800,15 +1745,13 @@ 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 @@ -1821,13 +1764,14 @@ 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 @@ -1838,15 +1782,13 @@ 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 @@ -1867,7 +1809,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() @@ -1882,10 +1824,9 @@ 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 @@ -1895,9 +1836,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 @@ -1909,10 +1850,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() @@ -1935,8 +1876,7 @@ 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 @@ -1958,10 +1898,9 @@ 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 @@ -1971,7 +1910,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 @@ -1986,14 +1925,13 @@ 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() @@ -2015,8 +1953,7 @@ 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) @@ -2028,7 +1965,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 @@ -2036,20 +1973,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 @@ -2066,8 +2003,7 @@ 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) @@ -2079,7 +2015,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 @@ -2087,20 +2023,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 @@ -2114,10 +2050,9 @@ 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) @@ -2129,7 +2064,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 @@ -2138,22 +2073,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 @@ -2168,8 +2103,7 @@ 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) @@ -2180,7 +2114,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): @@ -2188,15 +2122,16 @@ 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 @@ -2211,11 +2146,10 @@ 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) @@ -2225,10 +2159,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 @@ -2243,8 +2177,7 @@ 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) @@ -2254,8 +2187,7 @@ 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() @@ -2281,8 +2213,7 @@ 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) @@ -2293,8 +2224,7 @@ 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() @@ -2318,10 +2248,9 @@ 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) @@ -2332,8 +2261,7 @@ 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() @@ -2343,10 +2271,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 @@ -2359,17 +2287,16 @@ 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() @@ -2387,18 +2314,17 @@ 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() @@ -2416,21 +2342,19 @@ 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 @@ -2443,11 +2367,10 @@ 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): @@ -2457,8 +2380,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() @@ -2475,9 +2398,8 @@ 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) @@ -2490,8 +2412,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() @@ -2508,9 +2430,8 @@ 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) @@ -2532,15 +2453,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() @@ -2558,21 +2479,23 @@ 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() @@ -2590,20 +2513,19 @@ 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) @@ -2623,9 +2545,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( @@ -2637,21 +2559,20 @@ 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() @@ -2670,9 +2591,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) @@ -2685,25 +2606,24 @@ 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() @@ -2718,9 +2638,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) @@ -2733,26 +2653,25 @@ 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 @@ -2764,20 +2683,19 @@ 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 @@ -2786,22 +2704,21 @@ 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 @@ -2810,32 +2727,31 @@ 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 @@ -2850,11 +2766,10 @@ 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 @@ -2872,7 +2787,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 @@ -2880,7 +2795,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 @@ -2889,7 +2804,22 @@ 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+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==" + 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==' + ) binary_data = base64.b64decode(base64_data) await self._setup_share(storage_account_name, storage_account_key) @@ -2898,8 +2828,7 @@ 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 @@ -2924,15 +2853,13 @@ 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)) @@ -2957,14 +2884,13 @@ 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:]) @@ -2986,17 +2912,16 @@ 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() @@ -3013,8 +2938,7 @@ 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: @@ -3022,8 +2946,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) @@ -3043,15 +2967,13 @@ 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)) @@ -3060,8 +2982,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) @@ -3082,8 +3004,7 @@ 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) @@ -3092,8 +3013,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]) @@ -3113,8 +3034,7 @@ 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) @@ -3142,15 +3062,13 @@ 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)) @@ -3179,8 +3097,7 @@ 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 @@ -3207,15 +3124,13 @@ 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)) @@ -3238,7 +3153,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): @@ -3249,15 +3164,14 @@ 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 @@ -3268,15 +3182,14 @@ 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) @@ -3293,18 +3206,17 @@ 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) @@ -3320,14 +3232,13 @@ 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) @@ -3351,8 +3262,7 @@ 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) @@ -3374,8 +3284,7 @@ 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) @@ -3397,10 +3306,9 @@ 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 @@ -3425,10 +3333,9 @@ 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 @@ -3461,8 +3368,7 @@ 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() @@ -3474,19 +3380,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( @@ -3495,11 +3401,12 @@ 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() @@ -3531,10 +3438,9 @@ 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) + response = requests.get(file_client.url, timeout=15) # Assert assert response.ok @@ -3562,8 +3468,7 @@ 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() @@ -3576,6 +3481,7 @@ 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) @@ -3585,8 +3491,7 @@ 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() @@ -3602,8 +3507,7 @@ 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() @@ -3628,9 +3532,8 @@ 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) + credential=token) + response = requests.get(file_client.url, timeout=15) # Assert assert response.ok @@ -3652,11 +3555,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 @@ -3664,17 +3567,16 @@ 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) + credential=token) + response = requests.get(file_client.url, timeout=15) # 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() @@ -3683,7 +3585,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, @@ -3698,18 +3600,17 @@ 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) + 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) # 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() @@ -3732,11 +3633,10 @@ 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) + response = requests.delete(file_client.url, timeout=15) # Assert assert response.ok @@ -3750,13 +3650,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 @@ -3770,20 +3670,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): @@ -3794,15 +3694,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 @@ -3816,9 +3716,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) @@ -3827,7 +3727,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 @@ -3842,11 +3742,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() @@ -3863,14 +3763,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() @@ -3884,7 +3784,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) @@ -3893,17 +3793,16 @@ 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), props.file_attributes.replace(" " == "") + assert str(file_attributes).replace(' ', '') == props.file_attributes.replace(' ', ''), props.file_attributes assert file_creation_time == props.creation_time assert file_last_write_time == props.last_write_time assert file_change_time == props.change_time @@ -3915,11 +3814,13 @@ 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() @@ -3934,18 +3835,20 @@ 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 @@ -3965,19 +3868,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 @@ -3995,7 +3898,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) @@ -4010,7 +3913,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 @@ -4031,7 +3934,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) @@ -4046,7 +3949,7 @@ async def test_bad_audience_file_client(self, **kwargs): file_path=file_name, credential=token_credential, token_intent=TEST_INTENT, - audience=f"https://badaudience.file.core.windows.net", + audience='https://badaudience.file.core.windows.net' ) # Assert @@ -4061,20 +3964,18 @@ 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() @@ -4082,22 +3983,28 @@ 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 @@ -4106,7 +4013,8 @@ 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 @@ -4114,19 +4022,22 @@ 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() + @pytest.mark.skip("Legacy transports will not be supported moving forward") @FileSharePreparer() async def test_legacy_transport(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") @@ -4141,7 +4052,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() @@ -4158,6 +4069,7 @@ async def test_legacy_transport(self, **kwargs): file_data = await (await file_client.download_file()).readall() assert file_data == b"Hello Async World!" # data is fixed by mock transport + @pytest.mark.skip("Legacy transports will not be supported moving forward") @FileSharePreparer() async def test_legacy_transport_with_content_validation(self, **kwargs): storage_account_name = kwargs.pop("storage_account_name") @@ -4172,7 +4084,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!" @@ -4193,16 +4105,23 @@ 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" @@ -4224,11 +4143,12 @@ 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\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' + b'\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) @@ -4252,8 +4172,9 @@ 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\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' + b'\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) @@ -4275,8 +4196,7 @@ 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" @@ -4299,8 +4219,7 @@ 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) @@ -4325,7 +4244,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() @@ -4335,7 +4254,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() @@ -4345,7 +4264,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() @@ -4365,7 +4284,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 42667ce47aa5..5f2e492f8e8c 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,4 +1,3 @@ -# 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 @@ -8,6 +7,12 @@ 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, @@ -18,22 +23,18 @@ 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): @@ -48,25 +49,16 @@ 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 @@ -88,16 +80,12 @@ 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): @@ -109,12 +97,8 @@ 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 @@ -133,13 +117,8 @@ 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 @@ -149,22 +128,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): @@ -172,16 +151,15 @@ 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): @@ -195,15 +173,13 @@ 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): @@ -217,17 +193,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 @@ -236,8 +212,7 @@ 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", @@ -268,7 +243,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): @@ -277,13 +252,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.keys(): + for service_type in SERVICES: 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 @@ -300,7 +275,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 @@ -308,7 +283,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 @@ -318,16 +293,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.keys(): + for service_type in SERVICES: 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" @@ -344,17 +319,16 @@ 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): @@ -362,13 +336,12 @@ 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 @@ -383,27 +356,28 @@ 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): @@ -412,13 +386,12 @@ 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): @@ -427,17 +400,15 @@ 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): @@ -446,98 +417,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): + def test_create_service_with_custom_account_endpoint_path(self, **kwargs): # pylint: disable=too-many-statements 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") @@ -548,37 +519,35 @@ 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?') - @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" - ) + @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 @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 callback(response): + def first_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=callback) + service.get_service_properties(raw_response_hook=first_callback) # Act remove the echoed client request ID - def callback(response): + def second_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=callback) + service.get_service_properties(raw_response_hook=second_callback) @FileSharePreparer() @recorded_by_proxy @@ -590,8 +559,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) @@ -604,26 +573,23 @@ 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") @@ -637,14 +603,13 @@ 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): @@ -657,13 +622,16 @@ def test_error_with_malformed_conn_str(self, **kwargs): for service_type in SERVICES.items(): # Act with pytest.raises(ValueError) as e: - service = service_type[0].from_connection_string( - conn_str, share_name="test", directory_path="foo/bar", file_path="temp/dat" + 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() @@ -678,14 +646,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() @@ -700,8 +668,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 5c8eed177a92..ba315d445f0c 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,25 +7,27 @@ 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): @@ -41,25 +43,16 @@ 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 @@ -81,16 +74,12 @@ 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): @@ -102,12 +91,8 @@ 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 @@ -125,13 +110,8 @@ 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 @@ -141,22 +121,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): @@ -164,16 +144,15 @@ 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): @@ -187,15 +166,13 @@ 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): @@ -209,17 +186,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 @@ -228,8 +205,7 @@ 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", @@ -260,7 +236,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): @@ -269,13 +245,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.keys(): + for service_type in SERVICES: 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 @@ -292,7 +268,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 @@ -300,7 +276,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 @@ -312,14 +288,14 @@ def test_create_service_ipv6_custom_domain(self): hostname = "github.com" account_url = f"https://{hostname}" - for service_type in SERVICES.keys(): + for service_type in SERVICES: 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" @@ -336,17 +312,16 @@ 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): @@ -354,13 +329,12 @@ 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 @@ -375,15 +349,19 @@ 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 @@ -391,11 +369,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): @@ -404,12 +382,15 @@ 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() @@ -419,17 +400,15 @@ 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): @@ -438,99 +417,98 @@ 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): + async def test_create_service_with_custom_account_endpoint_path(self, **kwargs): # pylint: disable=too-many-statements 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 @@ -540,8 +518,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 @@ -550,11 +528,14 @@ 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) @@ -567,26 +548,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") @@ -597,17 +578,19 @@ 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): @@ -621,14 +604,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() @@ -643,8 +626,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 b4bf349f7288..eee68273f57a 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,6 +6,11 @@ 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, @@ -18,9 +23,6 @@ SmbMultichannel, ) -from devtools_testutils import recorded_by_proxy -from devtools_testutils.storage import StorageRecordedTestCase -from settings.testcase import FileSharePreparer # ------------------------------------------------------------------------------ @@ -37,7 +39,6 @@ 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: @@ -56,8 +57,7 @@ def _assert_cors_equal(self, cors1, cors2): assert len(cors1) == len(cors2) - for i in range(0, len(cors1)): - rule1 = cors1[i] + for i, rule1 in enumerate(cors1): rule2 = cors2[i] assert len(rule1.allowed_origins) == len(rule2.allowed_origins) assert len(rule1.allowed_methods) == len(rule2.allowed_methods) @@ -81,40 +81,45 @@ 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 - - with pytest.raises(TypeError): - ShareProtocolSettings(smb=ShareSmbSettings(multichannel=SmbMultichannel())) + 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()) 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() @@ -131,7 +136,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 @@ -140,16 +145,15 @@ 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 @@ -158,10 +162,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"] @@ -170,8 +174,7 @@ 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] @@ -180,7 +183,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() @@ -191,7 +194,9 @@ 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 @@ -202,10 +207,9 @@ 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 70b7ce7a2b33..56479ca76e49 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 @@ -25,6 +25,7 @@ ) from azure.storage.fileshare.aio import ShareServiceClient + # ------------------------------------------------------------------------------ @@ -40,7 +41,6 @@ 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,15 +94,18 @@ 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()) @@ -110,12 +113,15 @@ 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() @@ -132,7 +138,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 @@ -141,16 +147,15 @@ 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 @@ -159,10 +164,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"] @@ -171,8 +176,7 @@ 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] @@ -181,7 +185,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() @@ -193,7 +197,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 4478f5bd383f..f9ab7720b2b3 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,26 +1,25 @@ -# 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' # ------------------------------------------------------------------------------ @@ -36,29 +35,27 @@ 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) @@ -89,16 +86,15 @@ 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 @@ -114,18 +110,32 @@ 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+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==" + 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==' + ) 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 @@ -141,16 +151,15 @@ 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 @@ -172,11 +181,10 @@ 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() @@ -196,17 +204,15 @@ 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)) @@ -215,7 +221,11 @@ 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 @@ -227,17 +237,15 @@ 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)) @@ -246,7 +254,11 @@ 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 @@ -260,18 +272,16 @@ 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)) @@ -280,7 +290,11 @@ 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 @@ -293,12 +307,11 @@ 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() @@ -322,11 +335,10 @@ 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 = [] @@ -355,11 +367,10 @@ 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,17 +393,15 @@ 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)) @@ -416,17 +425,15 @@ 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)) @@ -452,18 +459,16 @@ 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)) @@ -492,20 +497,18 @@ 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: @@ -531,34 +534,30 @@ 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) @@ -579,34 +578,30 @@ 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) @@ -626,9 +621,8 @@ 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 @@ -639,26 +633,23 @@ 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) @@ -678,11 +669,10 @@ 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 @@ -692,7 +682,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() @@ -706,11 +696,10 @@ 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 @@ -730,16 +719,15 @@ 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 @@ -762,17 +750,15 @@ 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)) @@ -782,16 +768,20 @@ 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 @@ -803,11 +793,10 @@ 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: @@ -828,11 +817,10 @@ 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: @@ -858,11 +846,10 @@ 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 @@ -883,6 +870,7 @@ 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) @@ -890,11 +878,10 @@ 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 @@ -918,20 +905,19 @@ 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 @@ -945,36 +931,35 @@ 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 @@ -988,29 +973,30 @@ 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 @@ -1024,27 +1010,29 @@ 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 @@ -1053,21 +1041,20 @@ 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 @@ -1079,33 +1066,35 @@ 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 @@ -1117,11 +1106,10 @@ 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: @@ -1145,11 +1133,10 @@ 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: @@ -1171,20 +1158,18 @@ 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: @@ -1211,20 +1196,18 @@ 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: @@ -1245,18 +1228,16 @@ 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)) @@ -1265,7 +1246,11 @@ 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() @@ -1281,18 +1266,16 @@ 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)) @@ -1301,7 +1284,11 @@ 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() @@ -1315,11 +1302,10 @@ 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) @@ -1339,11 +1325,10 @@ 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) @@ -1351,14 +1336,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 @@ -1366,15 +1351,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) @@ -1388,15 +1373,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() @@ -1416,11 +1401,10 @@ 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)) @@ -1443,13 +1427,12 @@ 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) @@ -1473,13 +1456,12 @@ 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) @@ -1503,13 +1485,12 @@ 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 @@ -1518,7 +1499,10 @@ 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) @@ -1526,5 +1510,4 @@ 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 0d97b85fb20c..c15f490834e4 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,27 +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 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' # ------------------------------------------------------------------------------ @@ -39,15 +38,14 @@ 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: @@ -55,12 +53,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) @@ -90,16 +88,15 @@ 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 @@ -117,18 +114,32 @@ async def test_unicode_get_file_binary_data(self, **kwargs): # Arrange await self._setup(storage_account_name, storage_account_key) - 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==" + 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==' + ) 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 @@ -146,15 +157,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) @@ -179,11 +190,10 @@ 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) @@ -205,17 +215,15 @@ 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)) @@ -225,7 +233,11 @@ 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 @@ -238,17 +250,15 @@ 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)) @@ -258,7 +268,11 @@ 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 @@ -273,18 +287,16 @@ 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)) @@ -294,7 +306,11 @@ 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 @@ -307,12 +323,11 @@ 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() @@ -337,11 +352,10 @@ 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: @@ -368,11 +382,10 @@ 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 = [] @@ -402,17 +415,15 @@ 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)) @@ -439,17 +450,15 @@ 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)) @@ -478,18 +487,16 @@ 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)) @@ -521,20 +528,18 @@ 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: @@ -563,26 +568,23 @@ 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)) @@ -612,26 +614,23 @@ 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)) @@ -660,9 +659,8 @@ 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 @@ -673,18 +671,16 @@ 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)) @@ -713,24 +709,23 @@ 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() @@ -745,11 +740,10 @@ 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 @@ -772,15 +766,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) @@ -807,17 +801,15 @@ 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)) @@ -826,17 +818,22 @@ 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() @@ -850,11 +847,10 @@ 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: @@ -878,11 +874,10 @@ 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: @@ -911,11 +906,10 @@ 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 @@ -936,6 +930,7 @@ 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 @@ -944,18 +939,17 @@ 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 @@ -974,20 +968,19 @@ 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 @@ -1003,35 +996,36 @@ 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 @@ -1046,28 +1040,31 @@ 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 @@ -1082,28 +1079,30 @@ 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 @@ -1113,21 +1112,20 @@ 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 @@ -1141,34 +1139,36 @@ 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,11 +1181,10 @@ 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: @@ -1212,11 +1211,10 @@ 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: @@ -1241,20 +1239,18 @@ 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: @@ -1284,20 +1280,18 @@ 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: @@ -1321,18 +1315,16 @@ 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)) @@ -1342,7 +1334,11 @@ 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() @@ -1359,18 +1355,16 @@ 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)) @@ -1380,7 +1374,11 @@ 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() @@ -1395,11 +1393,10 @@ 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) @@ -1420,11 +1417,10 @@ 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) @@ -1433,14 +1429,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 @@ -1448,16 +1444,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) @@ -1471,16 +1467,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() @@ -1501,11 +1497,10 @@ 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)) @@ -1529,13 +1524,12 @@ 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) @@ -1560,13 +1554,12 @@ 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) @@ -1591,13 +1584,12 @@ 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 @@ -1606,7 +1598,10 @@ 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 0a97ab973a88..39b80c88c07c 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_handle.py +++ b/sdk/storage/azure-storage-file-share/tests/test_handle.py @@ -14,8 +14,9 @@ from azure.storage.fileshare import ShareServiceClient + # ------------------------------------------------------------------------------ -TEST_SHARE_NAME = "test-share" +TEST_SHARE_NAME = 'test-share' # ------------------------------------------------------------------------------ @@ -109,9 +110,10 @@ 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 @@ -131,7 +133,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)) @@ -157,7 +159,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()) @@ -183,13 +185,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() @@ -211,8 +213,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() @@ -225,19 +227,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 e374242c09a0..8b540ea2074f 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 @@ -13,8 +13,9 @@ import pytest from azure.storage.fileshare.aio import ShareServiceClient + # ------------------------------------------------------------------------------ -TEST_SHARE_NAME = "test-share" +TEST_SHARE_NAME = 'test-share' # ------------------------------------------------------------------------------ @@ -62,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() @@ -92,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() @@ -106,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 = [] @@ -117,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 cd4e59c81d99..1514a04858af 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_helpers.py +++ b/sdk/storage/azure-storage-file-share/tests/test_helpers.py @@ -4,12 +4,14 @@ # license information. # -------------------------------------------------------------------------- -from typing import Any, Dict, Iterator, Optional +from typing import Any, Dict, Optional + +from requests import Response from typing_extensions import Self +from urllib3 import HTTPResponse -from azure.core.pipeline.transport import HttpTransport +from azure.core.pipeline.transport import HttpTransport, RequestsTransportResponse # pylint: disable=no-name-in-module from azure.core.rest import HttpRequest -from azure.core.rest._http_response_impl import HttpResponseImpl class ProgressTracker: @@ -30,52 +32,34 @@ def assert_complete(self): assert self.total == self.current -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 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() class MockStorageTransport(HttpTransport): """ - This transport returns azure.core.rest HttpResponse objects for - compatibility with TypeSpec-generated code that uses iter_bytes/iter_raw. + This transport returns legacy http response objects from azure core and is + intended only to test our backwards compatibility support. """ - - def send(self, request: HttpRequest, **kwargs: Any) -> HttpResponseImpl: - if request.method == "GET": + def send(self, request: HttpRequest, **kwargs: Any) -> RequestsTransportResponse: + if request.method == 'GET': # download_file headers = { "Content-Type": "application/octet-stream", @@ -86,34 +70,54 @@ def send(self, request: HttpRequest, **kwargs: Any) -> HttpResponseImpl: if "x-ms-range-get-content-md5" in request.headers: headers["Content-MD5"] = "7Qdih1MuhjZehB6Sv8UNjA==" # cspell:disable-line - rest_response = _make_rest_response(request, b"Hello World!", headers) - elif request.method == "HEAD": + rest_response = RequestsTransportResponse( + request=request, + requests_response=MockHttpClientResponse( + request.url, + b"Hello World!", + headers, + ) + ) + elif request.method == 'HEAD': # get_file_properties - rest_response = _make_rest_response( - request, - b"", - { - "Content-Type": "application/octet-stream", - "Content-Length": "1024", - }, + rest_response = RequestsTransportResponse( + request=request, + requests_response=MockHttpClientResponse( + request.url, + b"", + { + "Content-Type": "application/octet-stream", + "Content-Length": "1024", + }, + ) ) - elif request.method == "PUT": + elif request.method == 'PUT': # upload_file - rest_response = _make_rest_response( - request, - b"", - {"Content-Length": "0"}, - 201, - "Created", + rest_response = RequestsTransportResponse( + request=request, + requests_response=MockHttpClientResponse( + request.url, + b"", + { + "Content-Length": "0", + }, + 201, + "Created" + ) ) - elif request.method == "DELETE": + elif request.method == 'DELETE': # delete_file - rest_response = _make_rest_response( - request, - b"", - {"Content-Length": "0"}, - 202, - "Accepted", + rest_response = RequestsTransportResponse( + request=request, + internal_response=MockHttpClientResponse( + request.url, + 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 3d5ef3a44ab5..7f8fe5970760 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,11 +4,16 @@ # license information. # -------------------------------------------------------------------------- -from typing import Any, AsyncIterator, Dict, Optional +import asyncio +from collections import deque +from typing import Any, Dict, Optional -from azure.core.pipeline.transport import AsyncHttpTransport +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.rest import HttpRequest -from azure.core.rest._http_response_impl_async import AsyncHttpResponseImpl class ProgressTracker: @@ -49,52 +54,35 @@ async def read(self, size: int = -1) -> bytes: return data -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 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 class MockStorageTransport(AsyncHttpTransport): """ - This transport returns azure.core.rest async HttpResponse objects for - compatibility with TypeSpec-generated code that uses iter_bytes/iter_raw. + This transport returns legacy http response objects from azure core and is + intended only to test our backwards compatibility support. """ - - async def send(self, request: HttpRequest, **kwargs: Any) -> AsyncHttpResponseImpl: - if request.method == "GET": + async def send(self, request: HttpRequest, **kwargs: Any) -> AioHttpTransportResponse: + if request.method == 'GET': # download_file headers = { "Content-Type": "application/octet-stream", @@ -105,37 +93,63 @@ async def send(self, request: HttpRequest, **kwargs: Any) -> AsyncHttpResponseIm if "x-ms-range-get-content-md5" in request.headers: headers["Content-MD5"] = "I3pVbaOCUTom+G9F9uKFoA==" - rest_response = _make_async_rest_response(request, b"Hello Async World!", headers) - elif request.method == "HEAD": + rest_response = AioHttpTransportResponse( + request=request, + aiohttp_response=MockAioHttpClientResponse( + request.url, + b"Hello Async World!", + headers, + ), + decompress=False + ) + elif request.method == 'HEAD': # get_file_properties - rest_response = _make_async_rest_response( - request, - b"", - { - "Content-Type": "application/octet-stream", - "Content-Length": "1024", - }, + rest_response = AioHttpTransportResponse( + request=request, + aiohttp_response=MockAioHttpClientResponse( + request.url, + b"", + { + "Content-Type": "application/octet-stream", + "Content-Length": "1024", + }, + ), + decompress=False ) - elif request.method == "PUT": + elif request.method == 'PUT': # upload_file - rest_response = _make_async_rest_response( - request, - b"", - {"Content-Length": "0"}, - 201, - "Created", + rest_response = AioHttpTransportResponse( + request=request, + aiohttp_response=MockAioHttpClientResponse( + request.url, + b"", + { + "Content-Length": "0", + }, + 201, + "Created" + ), + decompress=False ) - elif request.method == "DELETE": + elif request.method == 'DELETE': # delete_file - rest_response = _make_async_rest_response( - request, - b"", - {"Content-Length": "0"}, - 202, - "Accepted", + rest_response = AioHttpTransportResponse( + request=request, + aiohttp_response=MockAioHttpClientResponse( + request.url, + b"", + { + "Content-Length": "0", + }, + 202, + "Accepted" + ), + decompress=False ) 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 e9fc041b7b47..33b8a16159bf 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_nfs.py +++ b/sdk/storage/azure-storage-file-share/tests/test_nfs.py @@ -3,31 +3,30 @@ # 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 -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, -) +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.storage.fileshare import ( ContentSettings, - FileProperties, DirectoryProperties, - ShareFileClient, + FileProperties, ShareDirectoryClient, + ShareFileClient, 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): @@ -35,15 +34,17 @@ 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 @@ -62,12 +63,11 @@ 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 +83,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,21 +94,24 @@ 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 @@ -123,22 +126,28 @@ 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 @@ -147,10 +156,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) @@ -165,12 +174,14 @@ 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() @@ -179,9 +190,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) @@ -191,17 +202,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() @@ -217,29 +228,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 @@ -251,15 +262,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 @@ -271,32 +282,37 @@ 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 @@ -308,16 +324,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 6568e0fe21d7..3f368e15b851 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,27 +3,30 @@ # 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 -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 +import pytest from devtools_testutils.aio import recorded_by_proxy_async from devtools_testutils.storage.aio import AsyncStorageRecordedTestCase from settings.testcase import FileSharePreparer -TEST_INTENT = "backup" -TEST_FILE_PREFIX = "file" -TEST_DIRECTORY_PREFIX = "directory" +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' class TestStorageFileNFSAsync(AsyncStorageRecordedTestCase): @@ -31,19 +34,23 @@ 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 @@ -53,7 +60,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: @@ -67,12 +74,11 @@ 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 @@ -88,8 +94,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() @@ -99,21 +105,24 @@ 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 @@ -128,22 +137,28 @@ 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 @@ -152,10 +167,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) @@ -170,12 +185,14 @@ 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() @@ -184,9 +201,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) @@ -196,17 +213,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() @@ -222,29 +239,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 @@ -256,15 +273,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 @@ -276,34 +293,37 @@ 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 @@ -315,16 +335,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 0360f5367625..a51e1f0b3878 100644 --- a/sdk/storage/azure-storage-file-share/tests/test_share.py +++ b/sdk/storage/azure-storage-file-share/tests/test_share.py @@ -1,24 +1,29 @@ -# 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 +from azure.core.pipeline.transport import RequestsTransport # pylint: disable=no-name-in-module from azure.storage.fileshare import ( AccessPolicy, AccountSasPermissions, @@ -26,9 +31,7 @@ generate_account_sas, generate_file_sas, generate_share_sas, - Metrics, ResourceTypes, - RetentionPolicy, ShareAccessTier, ShareClient, ShareFileClient, @@ -39,16 +42,12 @@ 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") @@ -62,7 +61,6 @@ 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) @@ -78,28 +76,29 @@ 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): - try: - self.fsc.delete_share(l.name, delete_snapshots=True) - except: - pass + if l.name.startswith(prefix): + 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" @@ -136,7 +135,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() @@ -154,9 +153,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() @@ -179,14 +178,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) @@ -229,9 +228,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 @@ -252,11 +251,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): @@ -265,9 +264,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 @@ -283,8 +282,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 @@ -306,16 +305,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 @@ -324,10 +323,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) @@ -340,10 +339,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 @@ -356,11 +355,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() @@ -379,9 +378,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) @@ -397,10 +396,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 @@ -415,10 +414,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) @@ -427,9 +426,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 @@ -438,39 +437,41 @@ 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 @@ -481,10 +482,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) @@ -499,8 +500,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): @@ -563,7 +564,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() @@ -611,7 +612,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() @@ -717,7 +718,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) @@ -734,7 +735,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): @@ -770,17 +771,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() @@ -817,16 +818,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() @@ -837,7 +838,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() @@ -848,8 +849,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() @@ -860,7 +861,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() @@ -874,15 +875,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 @@ -891,8 +892,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)) @@ -911,7 +912,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) @@ -934,20 +935,19 @@ 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=dict()) + resp = share.set_share_access_policy(signed_identifiers={}) # 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(dict()) + resp = share.set_share_access_policy({}) # 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,15 +1410,16 @@ 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) @@ -1428,8 +1429,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() @@ -1440,12 +1441,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() @@ -1454,8 +1455,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() @@ -1466,29 +1467,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() @@ -1500,24 +1501,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 @@ -1527,9 +1528,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) @@ -1546,13 +1547,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) + response = requests.get(sas_client.url, timeout=15) # Assert assert response.ok @@ -1566,11 +1567,9 @@ 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 @@ -1591,27 +1590,25 @@ 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 @@ -1645,15 +1642,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()) @@ -1675,7 +1672,11 @@ 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 @@ -1685,7 +1686,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 @@ -1720,8 +1721,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 @@ -1731,29 +1732,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 @@ -1771,22 +1772,25 @@ 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 @@ -1804,9 +1808,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() @@ -1821,9 +1825,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() @@ -1851,7 +1855,11 @@ 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()) @@ -1875,10 +1883,12 @@ 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) @@ -1904,23 +1914,27 @@ def test_get_user_delegation_sas(self, **kwargs): @pytest.mark.live_test_only @FileSharePreparer() - def test_share_cross_tenant_sas(self, **kwargs): + def test_share_cross_tenant_sas(self, **kwargs): # pylint: disable=too-many-locals 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}) + decoded = jwt.decode(token.token, options={"verify_signature": False}) # pylint: disable=no-member 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 @@ -1942,14 +1956,16 @@ def test_share_cross_tenant_sas(self, **kwargs): 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 @@ -1963,19 +1979,20 @@ def test_share_cross_tenant_sas(self, **kwargs): 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 a12f3a836e98..1c109bedc581 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,23 +1,29 @@ -# 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 +from azure.core.pipeline.transport import AioHttpTransport # pylint: disable=no-name-in-module from azure.storage.fileshare import ( AccessPolicy, AccountSasPermissions, @@ -30,18 +36,13 @@ 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" # ------------------------------------------------------------------------------ @@ -62,10 +63,11 @@ 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): - try: - await self.fsc.delete_share(l.name, delete_snapshots=True) - except: - pass + if l.name.startswith(prefix): + try: + await self.fsc.delete_share(l.name, delete_snapshots=True) + except: + pass # --Helpers----------------------------------------------------------------- def _get_share_reference(self, prefix=TEST_SHARE_PREFIX): @@ -115,7 +117,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() @@ -133,11 +135,12 @@ 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): @@ -158,14 +161,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) @@ -211,9 +214,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 @@ -234,11 +237,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): @@ -247,9 +250,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 @@ -265,8 +268,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 @@ -288,16 +291,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 @@ -306,10 +309,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) @@ -322,10 +325,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 @@ -338,11 +341,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() @@ -361,9 +364,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) @@ -380,10 +383,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) @@ -399,10 +402,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) @@ -411,9 +414,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 @@ -422,39 +425,41 @@ 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 @@ -465,10 +470,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) @@ -483,8 +488,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): @@ -550,7 +555,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() @@ -598,7 +603,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() @@ -704,7 +709,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) @@ -721,7 +726,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): @@ -760,7 +765,10 @@ 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 @@ -770,10 +778,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() @@ -812,7 +820,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) @@ -821,9 +829,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() @@ -834,7 +842,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() @@ -848,8 +856,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() @@ -859,7 +867,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() @@ -873,15 +881,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 @@ -890,8 +898,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 = [] @@ -912,7 +920,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) @@ -937,7 +945,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)) @@ -950,9 +958,8 @@ 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) @@ -1012,7 +1019,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 @@ -1026,6 +1033,7 @@ 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): @@ -1034,7 +1042,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) @@ -1052,7 +1060,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() @@ -1071,7 +1079,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() @@ -1261,7 +1269,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() @@ -1309,7 +1317,7 @@ async def test_set_share_acl(self, **kwargs): await share.create_share() # Act - resp = await share.set_share_access_policy(signed_identifiers=dict()) + resp = await share.set_share_access_policy(signed_identifiers={}) # Assert acl = await share.get_share_access_policy() @@ -1327,12 +1335,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(dict()) + resp = await share.set_share_access_policy({}) # 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() @@ -1340,7 +1348,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() @@ -1348,9 +1356,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, @@ -1361,8 +1369,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 @@ -1380,15 +1388,13 @@ 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() @@ -1400,11 +1406,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 @@ -1416,10 +1422,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) + self.assertNamedItemInContainer(resp, 'dir1') + self.assertNamedItemInContainer(resp, 'dir2') + self.assertNamedItemInContainer(resp, 'file1') + await self._delete_shares(share.share_name) @FileSharePreparer() @recorded_by_proxy_async @@ -1428,19 +1434,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_name = await self._create_share() - dir1 = share_name.get_directory_client("dir1") + share = await self._create_share() + dir1 = share.get_directory_client('dir1') await dir1.create_directory() - dir2 = share_name.get_directory_client("dir2") + dir2 = share.get_directory_client('dir2') await dir2.create_directory() - snapshot1 = await share_name.create_snapshot() - dir3 = share_name.get_directory_client("dir3") + snapshot1 = await share.create_snapshot() + dir3 = share.get_directory_client('dir3') await dir3.create_directory() - file1 = share_name.get_file_client("file1") - await file1.upload_file("data") + file1 = share.get_file_client('file1') + await file1.upload_file('data') # Act - snapshot_client = self.fsc.get_share_client(share_name.share_name, snapshot=snapshot1) + snapshot_client = self.fsc.get_share_client(share.share_name, snapshot=snapshot1) resp = [] async for d in snapshot_client.list_directories_and_files(): resp.append(d) @@ -1449,9 +1455,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_name) + self.assertNamedItemInContainer(resp, 'dir1') + self.assertNamedItemInContainer(resp, 'dir2') + await self._delete_shares(share.share_name) @FileSharePreparer() @recorded_by_proxy_async @@ -1460,16 +1466,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_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") + 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') # Act - result = share_name.list_directories_and_files(results_per_page=2).by_page() + result = share.list_directories_and_files(results_per_page=2).by_page() results = [] async for r in await result.__anext__(): results.append(r) @@ -1477,9 +1483,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_name) + self.assertNamedItemInContainer(results, 'dir1') + self.assertNamedItemInContainer(results, 'filea1') + await self._delete_shares(share.share_name) @FileSharePreparer() @recorded_by_proxy_async @@ -1488,23 +1494,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_name = await self._create_share() - dir1 = share_name.get_directory_client("dir1") + share = await self._create_share() + dir1 = share.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_name.list_directories_and_files("dir1", results_per_page=2).by_page() + generator1 = share.list_directories_and_files( + 'dir1', results_per_page=2).by_page() result1 = [] async for r in await generator1.__anext__(): result1.append(r) - generator2 = share_name.list_directories_and_files("dir1", results_per_page=2).by_page( - continuation_token=generator1.continuation_token - ) + generator2 = share.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) @@ -1512,12 +1518,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_name) + await self._delete_shares(share.share_name) @FileSharePreparer() @recorded_by_proxy_async @@ -1527,27 +1533,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) + self.assertNamedItemInContainer(resp, 'pref_file2') + self.assertNamedItemInContainer(resp, 'pref_dir3') + await self._delete_shares(share.share_name) @pytest.mark.live_test_only @FileSharePreparer() @@ -1556,9 +1562,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) @@ -1574,12 +1580,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) + response = requests.get(sas_client.url, timeout=15) # Assert assert response.ok @@ -1593,11 +1599,9 @@ 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 @@ -1619,27 +1623,25 @@ 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 @@ -1674,9 +1676,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 = [] @@ -1684,7 +1686,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 = [] @@ -1708,7 +1710,9 @@ 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 @@ -1720,7 +1724,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 @@ -1750,8 +1754,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(): @@ -1763,29 +1767,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(): @@ -1805,22 +1809,25 @@ 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 @@ -1838,9 +1845,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() @@ -1855,9 +1862,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() @@ -1885,7 +1892,11 @@ 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(): @@ -1911,10 +1922,12 @@ 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) @@ -1940,23 +1953,27 @@ async def test_get_user_delegation_sas(self, **kwargs): @pytest.mark.live_test_only @FileSharePreparer() - async def test_share_cross_tenant_sas(self, **kwargs): + async def test_share_cross_tenant_sas(self, **kwargs): # pylint: disable=too-many-locals 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}) + decoded = jwt.decode(token.token, options={"verify_signature": False}) # pylint: disable=no-member 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 @@ -1978,14 +1995,16 @@ async def test_share_cross_tenant_sas(self, **kwargs): 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(): @@ -2001,14 +2020,16 @@ async def test_share_cross_tenant_sas(self, **kwargs): 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 From e07437d54583b62d00bdde65b5f36136edaa5353 Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Fri, 22 May 2026 09:05:54 -0700 Subject: [PATCH 44/45] regen with newest emitter --- .../azure/storage/fileshare/_download.py | 6 +- .../azure/storage/fileshare/_file_client.py | 39 +- .../azure/storage/fileshare/_file_client.pyi | 8 +- .../fileshare/_generated/_utils/model_base.py | 374 +++++++++++++++--- .../_generated/_utils/serialization.py | 23 +- .../fileshare/_generated/models/_models.py | 119 +++++- .../fileshare/_generated/models/_patch.py | 1 - .../azure/storage/fileshare/_models.py | 4 +- .../storage/fileshare/_shared/policies.py | 5 +- .../storage/fileshare/aio/_download_async.py | 7 +- .../fileshare/aio/_file_client_async.py | 37 +- .../fileshare/aio/_file_client_async.pyi | 8 +- 12 files changed, 515 insertions(+), 116 deletions(-) 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 46d5fc47300d..4f1f11300d54 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 @@ -119,9 +119,7 @@ def _write_to_stream(self, chunk_data: bytes, chunk_start: int) -> None: 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=is_md5_validation(self.validate_content) + chunk_start, chunk_end, check_content_md5=is_md5_validation(self.validate_content) ) try: @@ -297,7 +295,7 @@ def _initial_request(self): self._initial_range[1], start_range_required=False, end_range_required=False, - check_content_md5=is_md5_validation(self._validate_content) + check_content_md5=is_md5_validation(self._validate_content), ) try: 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 39e6aca5c9d4..f41c63a409a0 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 @@ -482,15 +482,12 @@ 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) - validate_content = parse_validation_option( - kwargs.pop('validate_content', None), - force_structured_message=True - ) - 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) + validate_content = parse_validation_option(kwargs.pop("validate_content", None), force_structured_message=True) + headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) data = kwargs.pop("data", None) file_http_headers = {} @@ -635,13 +632,10 @@ def upload_file( max_concurrency = kwargs.pop("max_concurrency", None) if max_concurrency is None: max_concurrency = DEFAULT_MAX_CONCURRENCY - validate_content = parse_validation_option( - kwargs.pop('validate_content', None), - force_structured_message=True - ) - progress_hook = kwargs.pop('progress_hook', None) - timeout = kwargs.pop('timeout', None) - encoding = kwargs.pop('encoding', 'UTF-8') + validate_content = parse_validation_option(kwargs.pop("validate_content", None), force_structured_message=True) + 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) @@ -966,7 +960,7 @@ def download_file( params = kwargs.pop("params", {}) or {} params["sharesnapshot"] = self.snapshot kwargs["params"] = params - validate_content = parse_validation_option(kwargs.pop('validate_content', None)) + validate_content = parse_validation_option(kwargs.pop("validate_content", None)) return StorageStreamDownloader( client=self._client.file, @@ -1401,13 +1395,10 @@ def upload_range(self, data: bytes, offset: int, length: int, **kwargs: Any) -> :returns: File-updated property dict (Etag and last modified). :rtype: Dict[str, Any] """ - validate_content = parse_validation_option( - kwargs.pop('validate_content', None), - force_structured_message=True - ) - timeout = kwargs.pop('timeout', None) - encoding = kwargs.pop('encoding', 'UTF-8') - file_last_write_mode = kwargs.pop('file_last_write_mode', None) + validate_content = parse_validation_option(kwargs.pop("validate_content", None), force_structured_message=True) + 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) diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client.pyi b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client.pyi index a517773f19ca..64deea3957e7 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client.pyi +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/_file_client.pyi @@ -134,7 +134,7 @@ class ShareFileClient(StorageAccountHostsMixin): file_mode: Optional[str] = None, file_property_semantics: Optional[Literal["New", "Restore"]] = None, data: Optional[bytes] = None, - validate_content: Optional[Literal['auto', 'crc64', 'md5']] = None, + validate_content: Optional[Literal["auto", "crc64", "md5"]] = None, timeout: Optional[int] = None, **kwargs: Any ) -> Dict[str, Any]: ... @@ -152,7 +152,7 @@ class ShareFileClient(StorageAccountHostsMixin): file_change_time: Optional[Union[str, datetime]] = None, metadata: Optional[Dict[str, str]] = None, content_settings: Optional[ContentSettings] = None, - validate_content: Optional[Union[bool, Literal['auto', 'crc64', 'md5']]] = None, + validate_content: Optional[Union[bool, Literal["auto", "crc64", "md5"]]] = None, max_concurrency: Optional[int] = None, lease: Optional[Union[ShareLeaseClient, str]] = None, progress_hook: Optional[Callable[[int, Optional[int]], None]] = None, @@ -200,7 +200,7 @@ class ShareFileClient(StorageAccountHostsMixin): length: Optional[int] = None, *, max_concurrency: Optional[int] = None, - validate_content: Optional[Union[bool, Literal['auto', 'crc64', 'md5']]] = None, + validate_content: Optional[Union[bool, Literal["auto", "crc64", "md5"]]] = None, lease: Optional[Union[ShareLeaseClient, str]] = None, progress_hook: Optional[Callable[[int, Optional[int]], None]] = None, decompress: Optional[bool] = None, @@ -271,7 +271,7 @@ class ShareFileClient(StorageAccountHostsMixin): offset: int, length: int, *, - validate_content: Optional[Union[bool, Literal['auto', 'crc64', 'md5']]] = None, + validate_content: Optional[Union[bool, Literal["auto", "crc64", "md5"]]] = None, encoding: str = "UTF-8", file_last_write_mode: Optional[Literal["preserve", "now"]] = None, lease: Optional[Union[ShareLeaseClient, str]] = None, 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 index 54f247904997..bd5b9caf1022 100644 --- 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 @@ -590,6 +590,239 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return _serialize(value, rf._format) +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + 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 + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param class Model(_MyMutableMapping): _is_model = True # label whether current class's _attr_to_rest_field has been calculated @@ -630,7 +863,9 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) super().__init__(dict_to_pass) - def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + 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. @@ -638,53 +873,89 @@ def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: :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: + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + 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, items) - elif not rf._is_optional: + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _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 + item = element.find(xml_name) + if item is not None: 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) + result[rf._rest_name] = _deserialize(rf._type, item) # rest thing is additional properties for e in element: @@ -721,6 +992,9 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf for attr, rf in cls._attr_to_rest_field.items() } + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -1105,6 +1379,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, original_tsp_name: typing.Optional[str] = None, ): self._type = type @@ -1118,6 +1393,7 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._deserializer = deserializer self._original_tsp_name = original_tsp_name @property @@ -1154,7 +1430,11 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # 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) + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + 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 @@ -1200,6 +1480,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, original_tsp_name: typing.Optional[str] = None, ) -> typing.Any: return _RestField( @@ -1210,6 +1491,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + deserializer=deserializer, original_tsp_name=original_tsp_name, ) @@ -1444,6 +1726,8 @@ def _deserialize_xml( value: str, ) -> typing.Any: element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) return _deserialize(deserializer, element) 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 954bf7ebffa7..a088671e9c51 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 @@ -1405,7 +1405,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: # Otherwise, result are unexpected self.additional_properties_detection = True - def __call__(self, target_obj, response_data, content_type=None): + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements """Call the deserializer to process a REST response. :param str target_obj: Target data type to deserialize to. @@ -1415,6 +1415,27 @@ def __call__(self, target_obj, response_data, content_type=None): :return: Deserialized object. :rtype: object """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) 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 index f58d1ee830ca..190731d9d6d3 100644 --- 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 @@ -9,9 +9,19 @@ # pylint: disable=useless-super-delegation import datetime +import functools from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload -from .._utils.model_base import Model as _Model, rest_field +from .._utils.model_base import ( + Model as _Model, + _xml_deser_bool, + _xml_deser_datetime_rfc7231, + _xml_deser_enum_or_str, + _xml_deser_int, + _xml_deser_str, + rest_field, +) +from ._enums import LeaseDurationType, LeaseStateType, LeaseStatusType, ShareRootSquash, StorageErrorCode if TYPE_CHECKING: from .. import models as _models @@ -31,16 +41,19 @@ class AccessPolicy(_Model): start: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The permissions for the ACL policy.""" @@ -78,11 +91,13 @@ class ClearRange(_Model): start: int = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + deserializer=_xml_deser_int, ) """Start of the range. Required.""" end: int = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "End", "text": False, "unwrapped": False}, + deserializer=_xml_deser_int, ) """End of the range. Required.""" @@ -137,6 +152,7 @@ class CorsRule(_Model): name="allowedOrigins", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "AllowedOrigins", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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 @@ -147,6 +163,7 @@ class CorsRule(_Model): name="allowedMethods", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "AllowedMethods", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The methods (HTTP request verbs) that the origin domain may use for a CORS request. (comma separated). Required.""" @@ -154,12 +171,14 @@ class CorsRule(_Model): name="allowedHeaders", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "AllowedHeaders", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The response headers that may be sent in the response to the CORS request and exposed by the browser to the request issuer. Required.""" @@ -167,6 +186,7 @@ class CorsRule(_Model): name="maxAgeInSeconds", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "MaxAgeInSeconds", "text": False, "unwrapped": False}, + deserializer=_xml_deser_int, ) """The maximum amount time that a browser should cache the preflight OPTIONS request. Required.""" @@ -218,6 +238,7 @@ class DirectoryItem(_Model): name="fileId", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "FileId", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The file ID.""" properties: Optional["_models.FileProperty"] = rest_field( @@ -228,12 +249,14 @@ class DirectoryItem(_Model): attributes: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Attributes", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The permission key.""" @@ -308,6 +331,7 @@ class Error(_Model): code: Optional[Union[str, "_models.StorageErrorCode"]] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Code", "text": False, "unwrapped": False}, + deserializer=functools.partial(_xml_deser_enum_or_str, StorageErrorCode), ) """The error code. Known values are: \"AccountAlreadyExists\", \"AccountBeingCreated\", \"AccountIsDisabled\", \"AuthenticationFailed\", \"AuthorizationFailure\", @@ -341,24 +365,28 @@ class Error(_Model): message: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Message", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """Copy source error message.""" @@ -410,6 +438,7 @@ class FileItem(_Model): name="fileId", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "FileId", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The file ID.""" properties: "_models.FileProperty" = rest_field( @@ -420,12 +449,14 @@ class FileItem(_Model): attributes: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Attributes", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The permission key.""" @@ -479,6 +510,7 @@ class FileProperty(_Model): name="contentLength", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Content-Length", "text": False, "unwrapped": False}, + deserializer=_xml_deser_int, ) """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 @@ -488,24 +520,28 @@ class FileProperty(_Model): name="creationTime", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "CreationTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The change time.""" last_modified: Optional[datetime.datetime] = rest_field( @@ -513,11 +549,13 @@ class FileProperty(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "Last-Modified", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """The last modified time.""" etag: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Etag", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The ETag of the file.""" @@ -559,11 +597,13 @@ class FileRange(_Model): start: int = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + deserializer=_xml_deser_int, ) """Start of the range. Required.""" end: int = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "End", "text": False, "unwrapped": False}, + deserializer=_xml_deser_int, ) """End of the range. Required.""" @@ -661,6 +701,7 @@ class HandleItem(_Model): name="handleId", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "HandleId", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """XSMB service handle ID. Required.""" path: "_models.StringEncoded" = rest_field( @@ -672,30 +713,35 @@ class HandleItem(_Model): name="fileId", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "FileId", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """Name of the client machine where the share is being mounted. Required.""" open_time: datetime.datetime = rest_field( @@ -703,6 +749,7 @@ class HandleItem(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "OpenTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """Time when the session that previously opened the handle has last been reconnected. (UTC). Required.""" @@ -711,6 +758,7 @@ class HandleItem(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "LastReconnectTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """Time handle was last connected to (UTC).""" access_right_list: Optional[list[Union[str, "_models.AccessRight"]]] = rest_field( @@ -769,17 +817,20 @@ class KeyInfo(_Model): start: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Start", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The delegated user tenant id in Azure AD.""" @@ -836,29 +887,34 @@ class ListFilesAndDirectoriesSegmentResponse(_Model): name="serviceEndpoint", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": True, "name": "ServiceEndpoint", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The share snapshot.""" encoded: Optional[bool] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": True, "name": "Encoded", "text": False, "unwrapped": False}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_str, ) """The directory path. Required.""" prefix: "_models.StringEncoded" = rest_field( @@ -869,12 +925,14 @@ class ListFilesAndDirectoriesSegmentResponse(_Model): marker: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Marker", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_int, ) """The max results.""" segment: "_models.FilesAndDirectoriesListSegment" = rest_field( @@ -886,12 +944,14 @@ class ListFilesAndDirectoriesSegmentResponse(_Model): name="nextMarker", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "NextMarker", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The directory ID.""" @@ -944,6 +1004,7 @@ class ListHandlesResponse(_Model): name="nextMarker", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "NextMarker", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The next marker. Required.""" @@ -989,22 +1050,26 @@ class ListSharesResponse(_Model): name="serviceEndpoint", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": True, "name": "ServiceEndpoint", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The service endpoint. Required.""" prefix: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Prefix", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The prefix.""" marker: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Marker", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_int, ) """The max results.""" share_items: Optional[list["_models.ShareItemInternal"]] = rest_field( @@ -1017,6 +1082,7 @@ class ListSharesResponse(_Model): name="nextMarker", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "NextMarker", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The next marker. Required.""" @@ -1062,17 +1128,20 @@ class Metrics(_Model): version: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Version", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_bool, ) """Indicates whether metrics should generate summary statistics for called API operations.""" retention_policy: Optional["_models.RetentionPolicy"] = rest_field( @@ -1120,12 +1189,14 @@ class RetentionPolicy(_Model): enabled: bool = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_int, ) """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 @@ -1214,21 +1285,25 @@ class ShareItemInternal(_Model): name: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Name", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The share name. Required.""" snapshot: Optional[str] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Snapshot", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """The share snapshot.""" deleted: Optional[bool] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Deleted", "text": False, "unwrapped": False}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_str, ) """The share version.""" properties: "_models.SharePropertiesInternal" = rest_field( @@ -1312,6 +1387,7 @@ class ShareNfsSettingsEncryptionInTransit(_Model): required: Optional[bool] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Required", "text": False, "unwrapped": False}, + deserializer=_xml_deser_bool, ) """If encryption in transit is required.""" @@ -1442,40 +1518,47 @@ class SharePropertiesInternal(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "Last-Modified", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """The last modified time. Required.""" etag: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Etag", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_int, ) """The provisioned bandwidth in MiBps.""" next_allowed_quota_downgrade_time: Optional[datetime.datetime] = rest_field( @@ -1483,6 +1566,7 @@ class SharePropertiesInternal(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "NextAllowedQuotaDowngradeTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """The next allowed quota downgrade time.""" deleted_time: Optional[datetime.datetime] = rest_field( @@ -1490,18 +1574,21 @@ class SharePropertiesInternal(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "DeletedTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_str, ) """The access tier.""" access_tier_change_time: Optional[datetime.datetime] = rest_field( @@ -1509,24 +1596,28 @@ class SharePropertiesInternal(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "AccessTierChangeTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=functools.partial(_xml_deser_enum_or_str, LeaseStatusType), ) """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}, + deserializer=functools.partial(_xml_deser_enum_or_str, LeaseStateType), ) """Lease state of the share. Known values are: \"available\", \"leased\", \"expired\", \"breaking\", and \"broken\".""" @@ -1534,6 +1625,7 @@ class SharePropertiesInternal(_Model): name="leaseDuration", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "LeaseDuration", "text": False, "unwrapped": False}, + deserializer=functools.partial(_xml_deser_enum_or_str, LeaseDurationType), ) """When a share is leased, specifies whether the lease is of infinite or fixed duration. Known values are: \"infinite\" and \"fixed\".""" @@ -1541,48 +1633,56 @@ class SharePropertiesInternal(_Model): name="enabledProtocols", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "EnabledProtocols", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=functools.partial(_xml_deser_enum_or_str, ShareRootSquash), ) """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}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_int, ) """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}, + deserializer=_xml_deser_int, ) """The maximum burst credits for IOPS.""" next_allowed_provisioned_iops_downgrade_time: Optional[datetime.datetime] = rest_field( @@ -1590,6 +1690,7 @@ class SharePropertiesInternal(_Model): visibility=["read", "create", "update", "delete", "query"], format="rfc7231", xml={"attribute": False, "name": "NextAllowedProvisionedIopsDowngradeTime", "text": False, "unwrapped": False}, + deserializer=_xml_deser_datetime_rfc7231, ) """The next allowed provisioned IOPS downgrade time.""" next_allowed_provisioned_bandwidth_downgrade_time: Optional[datetime.datetime] = rest_field( @@ -1602,12 +1703,14 @@ class SharePropertiesInternal(_Model): "text": False, "unwrapped": False, }, + deserializer=_xml_deser_datetime_rfc7231, ) """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}, + deserializer=_xml_deser_bool, ) """Whether SMB directory lease is enabled.""" @@ -1751,6 +1854,7 @@ class ShareSmbSettingsEncryptionInTransit(_Model): required: Optional[bool] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Required", "text": False, "unwrapped": False}, + deserializer=_xml_deser_bool, ) """If encryption in transit is required.""" @@ -1786,6 +1890,7 @@ class ShareStats(_Model): name="shareUsageBytes", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "ShareUsageBytes", "text": False, "unwrapped": False}, + deserializer=_xml_deser_int, ) """The approximate size of the data stored in bytes. Note that this value may not include all recently created or recently resized files. Required.""" @@ -1822,6 +1927,7 @@ class SignedIdentifier(_Model): id: str = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Id", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """A unique id. Required.""" access_policy: Optional["_models.AccessPolicy"] = rest_field( @@ -1903,6 +2009,7 @@ class SmbMultichannel(_Model): enabled: Optional[bool] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "Enabled", "text": False, "unwrapped": False}, + deserializer=_xml_deser_bool, ) """If SMB multichannel is enabled.""" @@ -1999,11 +2106,13 @@ class StringEncoded(_Model): encoded: Optional[bool] = rest_field( visibility=["read", "create", "update", "delete", "query"], xml={"attribute": True, "name": "Encoded", "text": False, "unwrapped": False}, + deserializer=_xml_deser_bool, ) """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}, + deserializer=_xml_deser_str, ) """The string content.""" @@ -2054,47 +2163,55 @@ class UserDelegationKey(_Model): name="signedOid", visibility=["read", "create", "update", "delete", "query"], xml={"attribute": False, "name": "SignedOid", "text": False, "unwrapped": False}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """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}, + deserializer=_xml_deser_str, ) """The key as a base64 string. Required.""" 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 96282242bb3b..671984cb89d8 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 @@ -16,7 +16,6 @@ from .._utils.model_base import Model as _deserialize from azure.core.serialization import as_attribute_dict - # --------------------------------------------------------------------------- # Backcompat shims for public methods that existed on the old autorest msrest models. # The TypeSpec-generated models inherit from ``_Model`` (a ``MutableMapping`` subclass) which does not 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 18569b895224..43b6826350e7 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 @@ -370,7 +370,7 @@ def __init__( # pylint: disable=unused-argument *, multichannel: Optional[SmbMultichannel] = None, encryption_in_transit: Optional[SmbEncryptionInTransit] = None, - **kwargs: Any + **kwargs: Any, ) -> None: super().__init__(multichannel=multichannel, encryption_in_transit=encryption_in_transit) if self.multichannel is None and self.encryption_in_transit is None: @@ -756,7 +756,7 @@ def __init__( content_disposition: Optional[str] = None, cache_control: Optional[str] = None, content_md5: Optional[bytearray] = None, - **kwargs: Any + **kwargs: Any, ) -> None: self.content_type = content_type or kwargs.get("Content-Type") self.content_encoding = content_encoding or kwargs.get("Content-Encoding") 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 113b241c1b84..345ea7fd9f86 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 @@ -470,14 +470,13 @@ def _validate_content_response( # Patch response to return response iterator wrapped in structured message decoder original_iter_bytes = response.http_response.iter_bytes - def wrapped_iter_bytes(*args, **kwargs): iterator = original_iter_bytes(*args, **kwargs) decoder = decoder_cls(iterator, content_length, block_size=DATA_BLOCK_SIZE) # Only set request/response if present on iterator - if hasattr(iterator, 'request'): + if hasattr(iterator, "request"): decoder.request = iterator.request # type: ignore - if hasattr(iterator, 'response'): + if hasattr(iterator, "response"): decoder.response = iterator.response # type: ignore return decoder 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 6690f2ae290e..11624b860816 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 @@ -78,9 +78,7 @@ 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=is_md5_validation(self.validate_content) + chunk_start, chunk_end, check_content_md5=is_md5_validation(self.validate_content) ) try: _, response = await cast( @@ -259,7 +257,8 @@ async def _initial_request(self): self._initial_range[1], start_range_required=False, end_range_required=False, - check_content_md5=is_md5_validation(self._validate_content)) + check_content_md5=is_md5_validation(self._validate_content), + ) try: location_mode, response = cast( 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 e1ee0f3b6ad7..188ab3ec5846 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 @@ -497,14 +497,11 @@ 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) - validate_content = parse_validation_option( - kwargs.pop('validate_content', None), - force_structured_message=True - ) + 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) + validate_content = parse_validation_option(kwargs.pop("validate_content", None), force_structured_message=True) headers = kwargs.pop("headers", {}) headers.update(add_metadata_headers(metadata)) data = kwargs.pop("data", None) @@ -648,13 +645,10 @@ async def upload_file( max_concurrency = kwargs.pop("max_concurrency", None) if max_concurrency is None: max_concurrency = DEFAULT_MAX_CONCURRENCY - validate_content = parse_validation_option( - kwargs.pop('validate_content', None), - force_structured_message=True - ) - progress_hook = kwargs.pop('progress_hook', None) - timeout = kwargs.pop('timeout', None) - encoding = kwargs.pop('encoding', 'UTF-8') + validate_content = parse_validation_option(kwargs.pop("validate_content", None), force_structured_message=True) + 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) @@ -983,7 +977,7 @@ async def download_file( params = kwargs.pop("params", {}) or {} params["sharesnapshot"] = self.snapshot kwargs["params"] = params - validate_content = parse_validation_option(kwargs.pop('validate_content', None)) + validate_content = parse_validation_option(kwargs.pop("validate_content", None)) downloader = StorageStreamDownloader( client=self._client.file, @@ -1418,13 +1412,10 @@ async def upload_range(self, data: bytes, offset: int, length: int, **kwargs: An :returns: File-updated property dict (Etag and last modified). :rtype: Dict[str, Any] """ - validate_content = parse_validation_option( - kwargs.pop('validate_content', None), - force_structured_message=True - ) - timeout = kwargs.pop('timeout', None) - encoding = kwargs.pop('encoding', 'UTF-8') - file_last_write_mode = kwargs.pop('file_last_write_mode', None) + validate_content = parse_validation_option(kwargs.pop("validate_content", None), force_structured_message=True) + 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 diff --git a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_file_client_async.pyi b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_file_client_async.pyi index 905f5a2bb002..49555a8964f4 100644 --- a/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_file_client_async.pyi +++ b/sdk/storage/azure-storage-file-share/azure/storage/fileshare/aio/_file_client_async.pyi @@ -135,7 +135,7 @@ class ShareFileClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin): file_mode: Optional[str] = None, file_property_semantics: Optional[Literal["New", "Restore"]] = None, data: Optional[bytes] = None, - validate_content: Optional[Literal['auto', 'crc64', 'md5']] = None, + validate_content: Optional[Literal["auto", "crc64", "md5"]] = None, timeout: Optional[int] = None, **kwargs: Any ) -> Dict[str, Any]: ... @@ -152,7 +152,7 @@ class ShareFileClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin): file_change_time: Optional[Union[str, datetime]] = None, metadata: Optional[Dict[str, str]] = None, content_settings: Optional[ContentSettings] = None, - validate_content: Optional[Union[bool, Literal['auto', 'crc64', 'md5']]] = None, + validate_content: Optional[Union[bool, Literal["auto", "crc64", "md5"]]] = None, max_concurrency: Optional[int] = None, lease: Optional[Union[ShareLeaseClient, str]] = None, progress_hook: Optional[Callable[[int, Optional[int]], Awaitable[None]]] = None, @@ -200,7 +200,7 @@ class ShareFileClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin): length: Optional[int] = None, *, max_concurrency: Optional[int] = None, - validate_content: Optional[Union[bool, Literal['auto', 'crc64', 'md5']]] = None, + validate_content: Optional[Union[bool, Literal["auto", "crc64", "md5"]]] = None, lease: Optional[Union[ShareLeaseClient, str]] = None, progress_hook: Optional[Callable[[int, Optional[int]], Awaitable[None]]] = None, decompress: Optional[bool] = None, @@ -271,7 +271,7 @@ class ShareFileClient(AsyncStorageAccountHostsMixin, StorageAccountHostsMixin): offset: int, length: int, *, - validate_content: Optional[Union[bool, Literal['auto', 'crc64', 'md5']]] = None, + validate_content: Optional[Union[bool, Literal["auto", "crc64", "md5"]]] = None, file_last_write_mode: Optional[Literal["preserve", "now"]] = None, lease: Optional[Union[ShareLeaseClient, str]] = None, encoding: str = "UTF-8", From 8c54c4e71c0c3f82a4d64c37f961669845934cbf Mon Sep 17 00:00:00 2001 From: Libba Lawrence Date: Tue, 26 May 2026 14:38:57 -0700 Subject: [PATCH 45/45] update policies --- .../storage/fileshare/_shared/policies.py | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) 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 345ea7fd9f86..8e45441c1543 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 @@ -467,20 +467,25 @@ def _validate_content_response( # Raises exception if missing content_length = int(response.http_response.headers[CONTENT_LENGTH_HEADER]) - # Patch response to return response iterator wrapped in structured message decoder - original_iter_bytes = response.http_response.iter_bytes - - def wrapped_iter_bytes(*args, **kwargs): - iterator = original_iter_bytes(*args, **kwargs) - decoder = decoder_cls(iterator, content_length, block_size=DATA_BLOCK_SIZE) - # Only set request/response if present on iterator - if hasattr(iterator, "request"): - decoder.request = iterator.request # type: ignore - if hasattr(iterator, "response"): - decoder.response = iterator.response # type: ignore - return decoder - - response.http_response.iter_bytes = wrapped_iter_bytes + def _make_wrapper(original): + def wrapped(*args, **kwargs): + iterator = original(*args, **kwargs) + decoder = decoder_cls(iterator, content_length, block_size=DATA_BLOCK_SIZE) + if hasattr(iterator, "request"): + decoder.request = iterator.request # type: ignore + if hasattr(iterator, "response"): + decoder.response = iterator.response # type: ignore + return decoder + return wrapped + + # Patch response to return response iterator wrapped in structured message decoder. + # TypeSpec-generated code calls iter_bytes()/iter_raw() instead of stream_download(). + if hasattr(response.http_response, "iter_bytes"): + response.http_response.iter_bytes = _make_wrapper(response.http_response.iter_bytes) + if hasattr(response.http_response, "iter_raw"): + response.http_response.iter_raw = _make_wrapper(response.http_response.iter_raw) + if hasattr(response.http_response, "stream_download"): + response.http_response.stream_download = _make_wrapper(response.http_response.stream_download) class StorageContentValidation(SansIOHTTPPolicy):