From c4e46d1c8d56c4f52a19b1156aa378a394483bce Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Thu, 14 Dec 2023 14:31:16 +0800 Subject: [PATCH 01/19] Add new params to support auto binding --- src/spring/HISTORY.md | 5 + src/spring/azext_spring/_app_factory.py | 17 + src/spring/azext_spring/_help.py | 2 + src/spring/azext_spring/_params.py | 11 +- .../azext_spring/_validators_enterprise.py | 31 + src/spring/azext_spring/app.py | 4 + ...t_app_create_binding_tanzu_components.yaml | 701 ++++++++++++++++++ .../azext_spring/tests/latest/test_asa_app.py | 12 + .../tests/latest/test_asa_app_scenario.py | 21 + src/spring/setup.py | 2 +- 10 files changed, 804 insertions(+), 2 deletions(-) create mode 100644 src/spring/azext_spring/tests/latest/recordings/test_app_create_binding_tanzu_components.yaml diff --git a/src/spring/HISTORY.md b/src/spring/HISTORY.md index 7e02a4d07c6..38ce813364f 100644 --- a/src/spring/HISTORY.md +++ b/src/spring/HISTORY.md @@ -1,5 +1,10 @@ Release History =============== +1.18.0 +--- +* Add arguments `--bind-service-registry` in `spring app create`. +* Add arguments `--bind-application-configuration-service` in `spring app create`. + 1.17.0 --- * Add arguments `--enable-api-try-out` in `spring api-portal update` diff --git a/src/spring/azext_spring/_app_factory.py b/src/spring/azext_spring/_app_factory.py index 31e3f9e200a..ccdaaa3ffb4 100644 --- a/src/spring/azext_spring/_app_factory.py +++ b/src/spring/azext_spring/_app_factory.py @@ -24,6 +24,7 @@ def _format_properties(self, **kwargs): kwargs['vnet_addons'] = self._load_vnet_addons(**kwargs) kwargs['ingress_settings'] = self._load_ingress_settings(**kwargs) kwargs['secrets'] = self._load_secrets_config(**kwargs) + kwargs['addon_configs'] = self._load_addon_configs(**kwargs) return models.AppResourceProperties(**kwargs) def _format_identity(self, system_assigned=None, user_assigned=None, **_): @@ -175,6 +176,22 @@ def _load_secrets_config(self, secrets=None, **_): return secret_var_def + def _load_addon_configs(self, bind_service_registry=None, bind_application_configuration_service=None, **_): + if not bind_service_registry and not bind_application_configuration_service: + return None + + addon_configs = {} + service_registry = {} + application_configuration_service = {} + + if bind_service_registry: + service_registry['resourceId'] = bind_service_registry + if bind_application_configuration_service: + application_configuration_service['resourceId'] = bind_application_configuration_service + + addon_configs['serviceRegistry'] = service_registry + addon_configs['applicationConfigurationService'] = application_configuration_service + return addon_configs class BasicTierApp(DefaultApp): def _get_persistent_disk_size(self, enable_persistent_storage, **_): diff --git a/src/spring/azext_spring/_help.py b/src/spring/azext_spring/_help.py index de0f6ef6015..3c7eda1bf0b 100644 --- a/src/spring/azext_spring/_help.py +++ b/src/spring/azext_spring/_help.py @@ -190,6 +190,8 @@ text: az spring app create -n MyApp -s MyCluster -g MyResourceGroup - name: Create an public accessible app with 3 instances and 2 cpu cores and 3 GB of memory per instance. text: az spring app create -n MyApp -s MyCluster -g MyResourceGroup --assign-endpoint true --cpu 2 --memory 3 --instance-count 3 + - name: Create an app binding to the default Service Registry and Application Configuration Service. + text: az spring app create -n MyApp -s MyCluster -g MyResourceGroup --bind-service-registry --bind-application-configuration-service """ helps['spring app append-persistent-storage'] = """ diff --git a/src/spring/azext_spring/_params.py b/src/spring/azext_spring/_params.py index c7f1d0921e1..91e5d704511 100644 --- a/src/spring/azext_spring/_params.py +++ b/src/spring/azext_spring/_params.py @@ -32,7 +32,8 @@ validate_acs_ssh_or_warn, validate_apm_properties, validate_apm_secrets, validate_apm_not_exist, validate_apm_update, validate_apm_reference, validate_apm_reference_and_enterprise_tier, validate_cert_reference, - validate_build_cert_reference, validate_acs_create, not_support_enterprise) + validate_build_cert_reference, validate_acs_create, not_support_enterprise, + validate_create_app_binding_default_application_configuration_service, validate_create_app_binding_default_service_registry) from ._app_validator import (fulfill_deployment_param, active_deployment_exist, ensure_not_active_deployment, validate_deloy_path, validate_deloyment_create_path, validate_cpu, validate_build_cpu, validate_memory, validate_build_memory, @@ -333,6 +334,14 @@ def load_arguments(self, _): nargs='+', validator=validate_create_app_with_user_identity_or_warning, help="Space-separated user-assigned managed identity resource IDs to assgin to an app.") + c.argument('bind_service_registry', + action='store_true', + validator=validate_create_app_binding_default_service_registry, + help='Bind the app to the default Service Registry automatically.') + c.argument('bind_application_configuration_service', + action='store_true', + validator=validate_create_app_binding_default_application_configuration_service, + help='Bind the app to the default Application Configuration Service automatically.') c.argument('cpu', arg_type=cpu_type) c.argument('memory', arg_type=memory_type) c.argument('instance_count', type=int, diff --git a/src/spring/azext_spring/_validators_enterprise.py b/src/spring/azext_spring/_validators_enterprise.py index 4bdd7212dfe..d057bfbcdd6 100644 --- a/src/spring/azext_spring/_validators_enterprise.py +++ b/src/spring/azext_spring/_validators_enterprise.py @@ -657,3 +657,34 @@ def validate_build_cert_reference(cmd, namespace): get_cert_resource_id(cert_names, cmd, namespace, result) namespace.build_certificates = result + + +def validate_create_app_binding_default_service_registry(cmd, namespace): + service_registry_resource = None + if namespace.bind_service_registry: + client = get_client(cmd) + service_registry_resources = list(client.service_registries.list(namespace.resource_group, namespace.service)) + if len(service_registry_resources) == 0: + raise ClientRequestError('App cannot bind to service registry because it is not configured.') + if len(service_registry_resources) > 1: + raise ClientRequestError('App cannot bind to multiple service registries.') + service_registry_resource = service_registry_resources[0] + normalize_bind_service_registry(namespace, namespace.bind_service_registry, service_registry_resource) + +def normalize_bind_service_registry(namespace, bind, service_registry_resource): + namespace.bind_service_registry = service_registry_resource.id if bind else None + +def validate_create_app_binding_default_application_configuration_service(cmd, namespace): + configuration_service_resource = None + if namespace.bind_application_configuration_service: + client = get_client(cmd) + acs_resources = list(client.configuration_services.list(namespace.resource_group, namespace.service)) + if len(acs_resources) == 0: + raise ClientRequestError('App cannot bind to application configuration service because it is not configured.') + if len(acs_resources) > 1: + raise ClientRequestError('App cannot bind to multiple application configuration services.') + configuration_service_resource = acs_resources[0] + normalize_bind_application_configuration_service(namespace, namespace.bind_application_configuration_service, configuration_service_resource) + +def normalize_bind_application_configuration_service(namespace, bind, configuration_service_resource): + namespace.bind_application_configuration_service = configuration_service_resource.id if bind else None diff --git a/src/spring/azext_spring/app.py b/src/spring/azext_spring/app.py index d83b0945031..9d0b0c4082f 100644 --- a/src/spring/azext_spring/app.py +++ b/src/spring/azext_spring/app.py @@ -53,6 +53,8 @@ def app_create(cmd, client, resource_group, service, name, assign_identity=None, system_assigned=None, user_assigned=None, + bind_service_registry=None, + bind_application_configuration_service=None, # app.update enable_persistent_storage=None, persistent_storage=None, @@ -115,6 +117,8 @@ def app_create(cmd, client, resource_group, service, name, create_app_kwargs = { 'system_assigned': system_assigned, 'user_assigned': user_assigned, + 'bind_service_registry': bind_service_registry, + 'bind_application_configuration_service': bind_application_configuration_service, 'enable_temporary_disk': True, 'enable_persistent_storage': enable_persistent_storage, 'persistent_storage': persistent_storage, diff --git a/src/spring/azext_spring/tests/latest/recordings/test_app_create_binding_tanzu_components.yaml b/src/spring/azext_spring/tests/latest/recordings/test_app_create_binding_tanzu_components.yaml new file mode 100644 index 00000000000..f0271e5f422 --- /dev/null +++ b/src/spring/azext_spring/tests/latest/recordings/test_app_create_binding_tanzu_components.yaml @@ -0,0 +1,701 @@ +interactions: +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/serviceRegistries?api-version=2023-11-01-preview + response: + body: + string: '{"value":[{"properties":{"provisioningState":"Succeeded","resourceRequests":{"cpu":"500m","memory":"1Gi","instanceCount":2},"instances":[{"name":"eureka-clitest000002-default-45e50-0","status":"Running"},{"name":"eureka-clitest000002-default-45e50-1","status":"Running"}]},"type":"Microsoft.AppPlatform/Spring/serviceRegistries","id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/serviceRegistries/default","name":"default","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:36:49.2595186Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:36:49.2595186Z"}}]}' + headers: + cache-control: + - no-cache + content-length: + - '760' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:49:08 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/configurationServices?api-version=2023-11-01-preview + response: + body: + string: '{"value":[{"properties":{"provisioningState":"Succeeded","resourceRequests":{"cpu":"500m","memory":"1Gi","instanceCount":2},"instances":[{"name":"application-configuration-service-674f48b866-tx8mp","status":"Running"},{"name":"application-configuration-service-674f48b866-xdsd2","status":"Running"}],"generation":"Gen1"},"type":"Microsoft.AppPlatform/Spring/configurationServices","id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/configurationServices/default","name":"default","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:36:43.4624828Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:36:43.4624828Z"}}]}' + headers: + cache-control: + - no-cache + content-length: + - '816' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:49:47 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003?api-version=2023-11-01-preview + response: + body: + string: '{"error":{"code":"NotFound","message":"App was not found","target":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003","details":null}}' + headers: + cache-control: + - no-cache + content-length: + - '241' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:50:27 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-resource-requests: + - '11999' + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 404 + message: Not Found +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002?api-version=2023-11-01-preview + response: + body: + string: '{"properties":{"provisioningState":"Succeeded","zoneRedundant":false,"version":3,"serviceId":"67b1366ccbe5493393823b200803b982","networkProfile":{"outboundIPs":{"publicIPs":["51.145.61.146","51.145.61.151"]},"outboundType":"loadBalancer"},"powerState":"Running","fqdn":"clitest000002.azuremicroservices.io","marketplaceResource":{"plan":"asa-ent-hr-mtr","publisher":"vmware-inc","product":"azure-spring-cloud-vmware-tanzu-2"}},"type":"Microsoft.AppPlatform/Spring","sku":{"name":"E0","tier":"Enterprise"},"location":"uksouth","tags":null,"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002","name":"clitest000002","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:14:48.8587695Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:14:48.8587695Z"}}' + headers: + cache-control: + - no-cache + content-length: + - '947' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:50:27 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-resource-requests: + - '11999' + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: '{"properties": {"public": false, "addonConfigs": {"serviceRegistry": {"resourceId": + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/serviceRegistries/default"}, + "applicationConfigurationService": {"resourceId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/configurationServices/default"}}, + "httpsOnly": false, "temporaryDisk": {"sizeInGB": 5, "mountPath": "/tmp"}, "enableEndToEndTLS": + false}}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + Content-Length: + - '576' + Content-Type: + - application/json + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: PUT + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003?api-version=2023-11-01-preview + response: + body: + string: '{"properties":{"addonConfigs":{"applicationConfigurationService":{"resourceId":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/configurationServices/default"},"serviceRegistry":{"resourceId":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/serviceRegistries/default"}},"public":false,"provisioningState":"Creating","httpsOnly":false,"temporaryDisk":{"sizeInGB":5,"mountPath":"/tmp"},"enableEndToEndTLS":false,"ingressSettings":{"readTimeoutInSeconds":300,"sendTimeoutInSeconds":60,"sessionCookieMaxAge":0,"sessionAffinity":"None","backendProtocol":"Default"}},"type":"Microsoft.AppPlatform/Spring/apps","identity":null,"location":"uksouth","id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003","name":"clitest000003","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:50:44.7761384Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:50:44.7761384Z"}}' + headers: + azure-asyncoperation: + - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/clitest000003/operationId/114a55a4-e07b-423c-8be3-002a79d40fa7?api-version=2023-11-01-preview&t=638380398454636552&c=MIIHHjCCBgagAwIBAgITfwI8YE7TFpH4swTJAgAEAjxgTjANBgkqhkiG9w0BAQsFADBEMRMwEQYKCZImiZPyLGQBGRYDR0JMMRMwEQYKCZImiZPyLGQBGRYDQU1FMRgwFgYDVQQDEw9BTUUgSW5mcmEgQ0EgMDIwHhcNMjMxMTAxMTI0ODMyWhcNMjQxMDI2MTI0ODMyWjBAMT4wPAYDVQQDEzVhc3luY29wZXJhdGlvbnNpZ25pbmdjZXJ0aWZpY2F0ZS5tYW5hZ2VtZW50LmF6dXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOfk7s1AnKyUqxJR1tGB1o-bd08yXoGVmNHQbpQb9IWlVS7htLxnfaUT083PrTqMEBOB9OS4hyPlFX-ApR1pomKdOD1y0gioSkZG_vgzN2wtFSBJWYWnrCl3xq-Tt9kIsLmZ7FZ-JBOTPKr8rSmKzm4L0NIsVf6UNGZOPdsZpFYEXOeyjshEO6PpPevESOM8rWMDozQTl1HzkC0gPrg5DGhYsJJe5HDWO8h7FZD5HFOCbb225KnGWZppoK08q2QpTgIP8P7CvjQnoGz2CnVSlOOMvuZXjhUTObsuZWO8XdgF04CkgZhq94b4Ej__vi4D1mZ2x9zRlrEMA1MEIfV5sN0CAwEAAaOCBAswggQHMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwEwCgYIKwYBBQUHAwIwPQYJKwYBBAGCNxUHBDAwLgYmKwYBBAGCNxUIhpDjDYTVtHiE8Ys-hZvdFs6dEoFggvX2K4Py0SACAWQCAQowggHaBggrBgEFBQcBAQSCAcwwggHIMGYGCCsGAQUFBzAChlpodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpaW5mcmEvQ2VydHMvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmwxLmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MFYGCCsGAQUFBzAChkpodHRwOi8vY3JsMi5hbWUuZ2JsL2FpYS9CTDJQS0lJTlRDQTAxLkFNRS5HQkxfQU1FJTIwSW5mcmElMjBDQSUyMDAyKDQpLmNydDBWBggrBgEFBQcwAoZKaHR0cDovL2NybDMuYW1lLmdibC9haWEvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmw0LmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MB0GA1UdDgQWBBRQX-Vd5gCv8ZxGaXD2PmaqqUHtdjAOBgNVHQ8BAf8EBAMCBaAwggE1BgNVHR8EggEsMIIBKDCCASSgggEgoIIBHIZCaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraWluZnJhL0NSTC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMS5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMi5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMy5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsNC5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JsMBcGA1UdIAQQMA4wDAYKKwYBBAGCN3sBATAfBgNVHSMEGDAWgBSuecJrXSWIEwb2BwnDl3x7l48dVTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAGraIc9hsqUGKcUfGRNlRfK3ussZT-LVHk7wo_N16Hnjq6O3kEOh1mdMNH-uYhMOeqXAg8ua2Co_Ryny1cSbWYBExXVxH2mDnGrRA0cOMEZVd7HGLhG7AvGMFDaxPDge9P_W4kaoMoN3Q3UcKwfZ3H94NyavU0Pk8lqY294YOkd-IgerbhZiIsIR1xE4QglniwVZCNl85WS-QtiJ2urgjIQ6mIdfAQb1mUbHPMh8i3z_av1Wjp5eOUm3MIA7j9kOWVnCEWM_wzDNrLBl-o3cRuUEdVMzmghLEyrN6p0svczMmPBFkSXArQzjyJpTQfM7UHrhAv7N0cUingZ7xJY8z_M&s=CciZyleHC5YiJ_8k3A-d_x3La_SNem6R-JosgeL-WEHNkdcdOVpqe4D7WhhDfxHujhkMM3p7zV5kmFn8DIF4gCUVCP7w8peD13hcavvUkKAYUNEwgq4MQ9g0Z9eC_adi49OHu1NGZ2C_nuBH2dN5K1yTj8J88wSEX_Zo-_KPr9HP1ZgqpqBNs8atDpQs1u1Z7LZEeFrxHzMZo_2P9EH9LUlE0ZNnZhmUg-zO6Dayg124VyOBAJEID-HMi8wtEGwXnhnIIZce0dbGZFnPoToRWZN2kV8sbZ2vlllubOlVFTm0HvzcbEyr48K-xYbTWOLDoOQSXFxvhbFIKseHqxDVzg&h=MsrI6JKNPzy_Z62L6P-llc804ksgcbOl93uM4k6PDX0 + cache-control: + - no-cache + content-length: + - '1247' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:50:45 GMT + expires: + - '-1' + location: + - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationResults/114a55a4-e07b-423c-8be3-002a79d40fa7/Spring/clitest000003?api-version=2023-11-01-preview&t=638380398454793634&c=MIIHHjCCBgagAwIBAgITfwI8YE7TFpH4swTJAgAEAjxgTjANBgkqhkiG9w0BAQsFADBEMRMwEQYKCZImiZPyLGQBGRYDR0JMMRMwEQYKCZImiZPyLGQBGRYDQU1FMRgwFgYDVQQDEw9BTUUgSW5mcmEgQ0EgMDIwHhcNMjMxMTAxMTI0ODMyWhcNMjQxMDI2MTI0ODMyWjBAMT4wPAYDVQQDEzVhc3luY29wZXJhdGlvbnNpZ25pbmdjZXJ0aWZpY2F0ZS5tYW5hZ2VtZW50LmF6dXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOfk7s1AnKyUqxJR1tGB1o-bd08yXoGVmNHQbpQb9IWlVS7htLxnfaUT083PrTqMEBOB9OS4hyPlFX-ApR1pomKdOD1y0gioSkZG_vgzN2wtFSBJWYWnrCl3xq-Tt9kIsLmZ7FZ-JBOTPKr8rSmKzm4L0NIsVf6UNGZOPdsZpFYEXOeyjshEO6PpPevESOM8rWMDozQTl1HzkC0gPrg5DGhYsJJe5HDWO8h7FZD5HFOCbb225KnGWZppoK08q2QpTgIP8P7CvjQnoGz2CnVSlOOMvuZXjhUTObsuZWO8XdgF04CkgZhq94b4Ej__vi4D1mZ2x9zRlrEMA1MEIfV5sN0CAwEAAaOCBAswggQHMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwEwCgYIKwYBBQUHAwIwPQYJKwYBBAGCNxUHBDAwLgYmKwYBBAGCNxUIhpDjDYTVtHiE8Ys-hZvdFs6dEoFggvX2K4Py0SACAWQCAQowggHaBggrBgEFBQcBAQSCAcwwggHIMGYGCCsGAQUFBzAChlpodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpaW5mcmEvQ2VydHMvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmwxLmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MFYGCCsGAQUFBzAChkpodHRwOi8vY3JsMi5hbWUuZ2JsL2FpYS9CTDJQS0lJTlRDQTAxLkFNRS5HQkxfQU1FJTIwSW5mcmElMjBDQSUyMDAyKDQpLmNydDBWBggrBgEFBQcwAoZKaHR0cDovL2NybDMuYW1lLmdibC9haWEvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmw0LmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MB0GA1UdDgQWBBRQX-Vd5gCv8ZxGaXD2PmaqqUHtdjAOBgNVHQ8BAf8EBAMCBaAwggE1BgNVHR8EggEsMIIBKDCCASSgggEgoIIBHIZCaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraWluZnJhL0NSTC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMS5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMi5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMy5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsNC5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JsMBcGA1UdIAQQMA4wDAYKKwYBBAGCN3sBATAfBgNVHSMEGDAWgBSuecJrXSWIEwb2BwnDl3x7l48dVTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAGraIc9hsqUGKcUfGRNlRfK3ussZT-LVHk7wo_N16Hnjq6O3kEOh1mdMNH-uYhMOeqXAg8ua2Co_Ryny1cSbWYBExXVxH2mDnGrRA0cOMEZVd7HGLhG7AvGMFDaxPDge9P_W4kaoMoN3Q3UcKwfZ3H94NyavU0Pk8lqY294YOkd-IgerbhZiIsIR1xE4QglniwVZCNl85WS-QtiJ2urgjIQ6mIdfAQb1mUbHPMh8i3z_av1Wjp5eOUm3MIA7j9kOWVnCEWM_wzDNrLBl-o3cRuUEdVMzmghLEyrN6p0svczMmPBFkSXArQzjyJpTQfM7UHrhAv7N0cUingZ7xJY8z_M&s=ufir1_DkO5Ys4n6pXDpxqTpKbaYcN37CVjt6l44H0ovoXmvLj6oKeDv3EXmJaeqyOegIaxAGWtTJIwAzJOO35kXJHjWOdWCjGi7kJEPTOfB5aKVThz67vdUn7ybt_VbScv5tEAvVp3zbL8DmXZOKYZ4yDLBM-fKrC-I7hDPmmuAdiUENYzvpUa7gStkWEubRltDEM2whUiuAbP9tLbreZQnAJzcfeNHm8igvYXCiz6y5LDlZ5PyH3_38LG5d_a_VXpnPBqiJageEuyloINRiWxQKIR4Ke-EBmJndLTDhVeLINrb5TJdgrmjGZ57wpVmJ1e6ff_vIcx0m9dYw9JpA2w&h=FxYRs6M943AreaY8x0rymgeT4V0DlCjRsuoxrvOsgdI + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-resource-requests: + - '1199' + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 201 + message: Created +- request: + body: null + headers: + Accept: + - '*/*' + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/clitest000003/operationId/114a55a4-e07b-423c-8be3-002a79d40fa7?api-version=2023-11-01-preview&t=638380398454636552&c=MIIHHjCCBgagAwIBAgITfwI8YE7TFpH4swTJAgAEAjxgTjANBgkqhkiG9w0BAQsFADBEMRMwEQYKCZImiZPyLGQBGRYDR0JMMRMwEQYKCZImiZPyLGQBGRYDQU1FMRgwFgYDVQQDEw9BTUUgSW5mcmEgQ0EgMDIwHhcNMjMxMTAxMTI0ODMyWhcNMjQxMDI2MTI0ODMyWjBAMT4wPAYDVQQDEzVhc3luY29wZXJhdGlvbnNpZ25pbmdjZXJ0aWZpY2F0ZS5tYW5hZ2VtZW50LmF6dXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOfk7s1AnKyUqxJR1tGB1o-bd08yXoGVmNHQbpQb9IWlVS7htLxnfaUT083PrTqMEBOB9OS4hyPlFX-ApR1pomKdOD1y0gioSkZG_vgzN2wtFSBJWYWnrCl3xq-Tt9kIsLmZ7FZ-JBOTPKr8rSmKzm4L0NIsVf6UNGZOPdsZpFYEXOeyjshEO6PpPevESOM8rWMDozQTl1HzkC0gPrg5DGhYsJJe5HDWO8h7FZD5HFOCbb225KnGWZppoK08q2QpTgIP8P7CvjQnoGz2CnVSlOOMvuZXjhUTObsuZWO8XdgF04CkgZhq94b4Ej__vi4D1mZ2x9zRlrEMA1MEIfV5sN0CAwEAAaOCBAswggQHMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwEwCgYIKwYBBQUHAwIwPQYJKwYBBAGCNxUHBDAwLgYmKwYBBAGCNxUIhpDjDYTVtHiE8Ys-hZvdFs6dEoFggvX2K4Py0SACAWQCAQowggHaBggrBgEFBQcBAQSCAcwwggHIMGYGCCsGAQUFBzAChlpodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpaW5mcmEvQ2VydHMvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmwxLmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MFYGCCsGAQUFBzAChkpodHRwOi8vY3JsMi5hbWUuZ2JsL2FpYS9CTDJQS0lJTlRDQTAxLkFNRS5HQkxfQU1FJTIwSW5mcmElMjBDQSUyMDAyKDQpLmNydDBWBggrBgEFBQcwAoZKaHR0cDovL2NybDMuYW1lLmdibC9haWEvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmw0LmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MB0GA1UdDgQWBBRQX-Vd5gCv8ZxGaXD2PmaqqUHtdjAOBgNVHQ8BAf8EBAMCBaAwggE1BgNVHR8EggEsMIIBKDCCASSgggEgoIIBHIZCaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraWluZnJhL0NSTC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMS5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMi5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMy5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsNC5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JsMBcGA1UdIAQQMA4wDAYKKwYBBAGCN3sBATAfBgNVHSMEGDAWgBSuecJrXSWIEwb2BwnDl3x7l48dVTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAGraIc9hsqUGKcUfGRNlRfK3ussZT-LVHk7wo_N16Hnjq6O3kEOh1mdMNH-uYhMOeqXAg8ua2Co_Ryny1cSbWYBExXVxH2mDnGrRA0cOMEZVd7HGLhG7AvGMFDaxPDge9P_W4kaoMoN3Q3UcKwfZ3H94NyavU0Pk8lqY294YOkd-IgerbhZiIsIR1xE4QglniwVZCNl85WS-QtiJ2urgjIQ6mIdfAQb1mUbHPMh8i3z_av1Wjp5eOUm3MIA7j9kOWVnCEWM_wzDNrLBl-o3cRuUEdVMzmghLEyrN6p0svczMmPBFkSXArQzjyJpTQfM7UHrhAv7N0cUingZ7xJY8z_M&s=CciZyleHC5YiJ_8k3A-d_x3La_SNem6R-JosgeL-WEHNkdcdOVpqe4D7WhhDfxHujhkMM3p7zV5kmFn8DIF4gCUVCP7w8peD13hcavvUkKAYUNEwgq4MQ9g0Z9eC_adi49OHu1NGZ2C_nuBH2dN5K1yTj8J88wSEX_Zo-_KPr9HP1ZgqpqBNs8atDpQs1u1Z7LZEeFrxHzMZo_2P9EH9LUlE0ZNnZhmUg-zO6Dayg124VyOBAJEID-HMi8wtEGwXnhnIIZce0dbGZFnPoToRWZN2kV8sbZ2vlllubOlVFTm0HvzcbEyr48K-xYbTWOLDoOQSXFxvhbFIKseHqxDVzg&h=MsrI6JKNPzy_Z62L6P-llc804ksgcbOl93uM4k6PDX0 + response: + body: + string: '{"id":"subscriptions/6c933f90-8115-4392-90f2-7077c9fa5dbd/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/clitest000003/operationId/114a55a4-e07b-423c-8be3-002a79d40fa7","name":"114a55a4-e07b-423c-8be3-002a79d40fa7","status":"Succeeded","startTime":"2023-12-13T04:50:45.3001101Z","endTime":"2023-12-13T04:50:45.5630799Z"}' + headers: + cache-control: + - no-cache + content-length: + - '371' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:50:45 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - '*/*' + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003?api-version=2023-11-01-preview + response: + body: + string: '{"properties":{"addonConfigs":{"applicationConfigurationService":{"resourceId":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/configurationServices/default"},"serviceRegistry":{"resourceId":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/serviceRegistries/default"}},"public":false,"provisioningState":"Succeeded","fqdn":"clitest000002.azuremicroservices.io","httpsOnly":false,"temporaryDisk":{"sizeInGB":5,"mountPath":"/tmp"},"persistentDisk":{"sizeInGB":0,"mountPath":"/persistent"},"enableEndToEndTLS":false,"ingressSettings":{"readTimeoutInSeconds":300,"sendTimeoutInSeconds":60,"sessionCookieMaxAge":0,"sessionAffinity":"None","backendProtocol":"Default"}},"type":"Microsoft.AppPlatform/Spring/apps","identity":null,"location":"uksouth","id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003","name":"clitest000003","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:50:44.7761384Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:50:44.7761384Z"}}' + headers: + cache-control: + - no-cache + content-length: + - '1351' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:50:46 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-resource-requests: + - '11998' + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: '{"properties": {"source": {"type": "BuildResult", "buildResultId": ""}, + "deploymentSettings": {"resourceRequests": {"cpu": "1", "memory": "1Gi"}, "scale": + {"minReplicas": 1, "maxReplicas": 10}}, "active": true}, "sku": {"name": "E0", + "tier": "Enterprise", "capacity": 1}}' + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + Content-Length: + - '280' + Content-Type: + - application/json + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: PUT + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003/deployments/mock-deployment?api-version=2023-11-01-preview + response: + body: + string: '{"properties":{"deploymentSettings":{"resourceRequests":{"cpu":"1","memory":"1Gi"},"environmentVariables":null,"terminationGracePeriodSeconds":90},"provisioningState":"Creating","status":"Running","active":true,"instances":null,"source":{"type":"BuildResult","buildResultId":""}},"type":"Microsoft.AppPlatform/Spring/apps/deployments","sku":{"name":"E0","tier":"Enterprise","capacity":1},"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003/deployments/default","name":"default","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:50:52.8076132Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:50:52.8076132Z"}}' + headers: + azure-asyncoperation: + - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/default/operationId/3b425f23-04c5-4d40-ad6a-eee9ceabdf5a?api-version=2023-11-01-preview&t=638380398536670111&c=MIIHHjCCBgagAwIBAgITfwI8YE7TFpH4swTJAgAEAjxgTjANBgkqhkiG9w0BAQsFADBEMRMwEQYKCZImiZPyLGQBGRYDR0JMMRMwEQYKCZImiZPyLGQBGRYDQU1FMRgwFgYDVQQDEw9BTUUgSW5mcmEgQ0EgMDIwHhcNMjMxMTAxMTI0ODMyWhcNMjQxMDI2MTI0ODMyWjBAMT4wPAYDVQQDEzVhc3luY29wZXJhdGlvbnNpZ25pbmdjZXJ0aWZpY2F0ZS5tYW5hZ2VtZW50LmF6dXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOfk7s1AnKyUqxJR1tGB1o-bd08yXoGVmNHQbpQb9IWlVS7htLxnfaUT083PrTqMEBOB9OS4hyPlFX-ApR1pomKdOD1y0gioSkZG_vgzN2wtFSBJWYWnrCl3xq-Tt9kIsLmZ7FZ-JBOTPKr8rSmKzm4L0NIsVf6UNGZOPdsZpFYEXOeyjshEO6PpPevESOM8rWMDozQTl1HzkC0gPrg5DGhYsJJe5HDWO8h7FZD5HFOCbb225KnGWZppoK08q2QpTgIP8P7CvjQnoGz2CnVSlOOMvuZXjhUTObsuZWO8XdgF04CkgZhq94b4Ej__vi4D1mZ2x9zRlrEMA1MEIfV5sN0CAwEAAaOCBAswggQHMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwEwCgYIKwYBBQUHAwIwPQYJKwYBBAGCNxUHBDAwLgYmKwYBBAGCNxUIhpDjDYTVtHiE8Ys-hZvdFs6dEoFggvX2K4Py0SACAWQCAQowggHaBggrBgEFBQcBAQSCAcwwggHIMGYGCCsGAQUFBzAChlpodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpaW5mcmEvQ2VydHMvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmwxLmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MFYGCCsGAQUFBzAChkpodHRwOi8vY3JsMi5hbWUuZ2JsL2FpYS9CTDJQS0lJTlRDQTAxLkFNRS5HQkxfQU1FJTIwSW5mcmElMjBDQSUyMDAyKDQpLmNydDBWBggrBgEFBQcwAoZKaHR0cDovL2NybDMuYW1lLmdibC9haWEvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmw0LmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MB0GA1UdDgQWBBRQX-Vd5gCv8ZxGaXD2PmaqqUHtdjAOBgNVHQ8BAf8EBAMCBaAwggE1BgNVHR8EggEsMIIBKDCCASSgggEgoIIBHIZCaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraWluZnJhL0NSTC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMS5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMi5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMy5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsNC5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JsMBcGA1UdIAQQMA4wDAYKKwYBBAGCN3sBATAfBgNVHSMEGDAWgBSuecJrXSWIEwb2BwnDl3x7l48dVTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAGraIc9hsqUGKcUfGRNlRfK3ussZT-LVHk7wo_N16Hnjq6O3kEOh1mdMNH-uYhMOeqXAg8ua2Co_Ryny1cSbWYBExXVxH2mDnGrRA0cOMEZVd7HGLhG7AvGMFDaxPDge9P_W4kaoMoN3Q3UcKwfZ3H94NyavU0Pk8lqY294YOkd-IgerbhZiIsIR1xE4QglniwVZCNl85WS-QtiJ2urgjIQ6mIdfAQb1mUbHPMh8i3z_av1Wjp5eOUm3MIA7j9kOWVnCEWM_wzDNrLBl-o3cRuUEdVMzmghLEyrN6p0svczMmPBFkSXArQzjyJpTQfM7UHrhAv7N0cUingZ7xJY8z_M&s=KvjeupbGgmQnr0S-w-uRnG8nInZrijZ5tkeghgpWdU5r0UZV9422t7Re0VSNLwl0i9JXYWFg6uA1EF6L0Z90-KJACREMQuPJZJtPyjj6FR9Xc3eFfzB3exvIi88_-13NF6HCPyndKU4TlRCYy8BTsie1g88kp8ZrBGA8tHI16OQag8X6fHP39LTBt-fc8P1goPFoIj-ZZvPgvmnTppwCGo_3EnxHenUmHFSX_Mukrh5SvPQEJC_GIbttLPS6sFWinqvbjp7lr9Xrt1gB1EowoCXA9VCQf3nRwDxFa6LT6RWy-Spb992Mv2uHnzG2Wk0UqDGhvHY5Bt3RKWA3He4rHA&h=SlYQj2yR92-HSIy0FXRCUxOv8fHkj3w-SML6DiHgpew + cache-control: + - no-cache + content-length: + - '839' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:50:53 GMT + expires: + - '-1' + location: + - https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationResults/3b425f23-04c5-4d40-ad6a-eee9ceabdf5a/Spring/default?api-version=2023-11-01-preview&t=638380398536670111&c=MIIHHjCCBgagAwIBAgITfwI8YE7TFpH4swTJAgAEAjxgTjANBgkqhkiG9w0BAQsFADBEMRMwEQYKCZImiZPyLGQBGRYDR0JMMRMwEQYKCZImiZPyLGQBGRYDQU1FMRgwFgYDVQQDEw9BTUUgSW5mcmEgQ0EgMDIwHhcNMjMxMTAxMTI0ODMyWhcNMjQxMDI2MTI0ODMyWjBAMT4wPAYDVQQDEzVhc3luY29wZXJhdGlvbnNpZ25pbmdjZXJ0aWZpY2F0ZS5tYW5hZ2VtZW50LmF6dXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOfk7s1AnKyUqxJR1tGB1o-bd08yXoGVmNHQbpQb9IWlVS7htLxnfaUT083PrTqMEBOB9OS4hyPlFX-ApR1pomKdOD1y0gioSkZG_vgzN2wtFSBJWYWnrCl3xq-Tt9kIsLmZ7FZ-JBOTPKr8rSmKzm4L0NIsVf6UNGZOPdsZpFYEXOeyjshEO6PpPevESOM8rWMDozQTl1HzkC0gPrg5DGhYsJJe5HDWO8h7FZD5HFOCbb225KnGWZppoK08q2QpTgIP8P7CvjQnoGz2CnVSlOOMvuZXjhUTObsuZWO8XdgF04CkgZhq94b4Ej__vi4D1mZ2x9zRlrEMA1MEIfV5sN0CAwEAAaOCBAswggQHMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwEwCgYIKwYBBQUHAwIwPQYJKwYBBAGCNxUHBDAwLgYmKwYBBAGCNxUIhpDjDYTVtHiE8Ys-hZvdFs6dEoFggvX2K4Py0SACAWQCAQowggHaBggrBgEFBQcBAQSCAcwwggHIMGYGCCsGAQUFBzAChlpodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpaW5mcmEvQ2VydHMvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmwxLmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MFYGCCsGAQUFBzAChkpodHRwOi8vY3JsMi5hbWUuZ2JsL2FpYS9CTDJQS0lJTlRDQTAxLkFNRS5HQkxfQU1FJTIwSW5mcmElMjBDQSUyMDAyKDQpLmNydDBWBggrBgEFBQcwAoZKaHR0cDovL2NybDMuYW1lLmdibC9haWEvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmw0LmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MB0GA1UdDgQWBBRQX-Vd5gCv8ZxGaXD2PmaqqUHtdjAOBgNVHQ8BAf8EBAMCBaAwggE1BgNVHR8EggEsMIIBKDCCASSgggEgoIIBHIZCaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraWluZnJhL0NSTC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMS5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMi5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMy5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsNC5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JsMBcGA1UdIAQQMA4wDAYKKwYBBAGCN3sBATAfBgNVHSMEGDAWgBSuecJrXSWIEwb2BwnDl3x7l48dVTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAGraIc9hsqUGKcUfGRNlRfK3ussZT-LVHk7wo_N16Hnjq6O3kEOh1mdMNH-uYhMOeqXAg8ua2Co_Ryny1cSbWYBExXVxH2mDnGrRA0cOMEZVd7HGLhG7AvGMFDaxPDge9P_W4kaoMoN3Q3UcKwfZ3H94NyavU0Pk8lqY294YOkd-IgerbhZiIsIR1xE4QglniwVZCNl85WS-QtiJ2urgjIQ6mIdfAQb1mUbHPMh8i3z_av1Wjp5eOUm3MIA7j9kOWVnCEWM_wzDNrLBl-o3cRuUEdVMzmghLEyrN6p0svczMmPBFkSXArQzjyJpTQfM7UHrhAv7N0cUingZ7xJY8z_M&s=Yt1sUui9BvbzWP_VJ99W_xbiStjuEYPmFP4ceA8H4LIwI6fKF0mIO1tXKn7Xp3zAqD4z9xc0RtGbYOdL220ZwlTjTt3g8XI3funb2T7c2hnA4AxS7SV9YvkuAi-N4MOrLrQK_X4zHy0h6zZRQGlJA5foDEgVuyncums9_pWvFjp5JLcItpT73i8eXtGkgAs5P_Vs5vZYb4E-u3MKOpvMp0cU8GeWGQeYOpa9v-LbXU8Jolg7v8N_OpiRE41dJjo4Om6cQR3QPyEFJx_W0XwJfwMgJ4HM_wsKCvt39F4t7OQmFvtjZbiDVtwX-dCWmXx8LhaP-zlZOf20aCzMcg339A&h=S5JLEe7tGcO6yd_4HaYQ7yZVcA4qZd8nVbUBpS3c2eo + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-resource-requests: + - '1199' + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 201 + message: Created +- request: + body: null + headers: + Accept: + - '*/*' + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/default/operationId/3b425f23-04c5-4d40-ad6a-eee9ceabdf5a?api-version=2023-11-01-preview&t=638380398536670111&c=MIIHHjCCBgagAwIBAgITfwI8YE7TFpH4swTJAgAEAjxgTjANBgkqhkiG9w0BAQsFADBEMRMwEQYKCZImiZPyLGQBGRYDR0JMMRMwEQYKCZImiZPyLGQBGRYDQU1FMRgwFgYDVQQDEw9BTUUgSW5mcmEgQ0EgMDIwHhcNMjMxMTAxMTI0ODMyWhcNMjQxMDI2MTI0ODMyWjBAMT4wPAYDVQQDEzVhc3luY29wZXJhdGlvbnNpZ25pbmdjZXJ0aWZpY2F0ZS5tYW5hZ2VtZW50LmF6dXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOfk7s1AnKyUqxJR1tGB1o-bd08yXoGVmNHQbpQb9IWlVS7htLxnfaUT083PrTqMEBOB9OS4hyPlFX-ApR1pomKdOD1y0gioSkZG_vgzN2wtFSBJWYWnrCl3xq-Tt9kIsLmZ7FZ-JBOTPKr8rSmKzm4L0NIsVf6UNGZOPdsZpFYEXOeyjshEO6PpPevESOM8rWMDozQTl1HzkC0gPrg5DGhYsJJe5HDWO8h7FZD5HFOCbb225KnGWZppoK08q2QpTgIP8P7CvjQnoGz2CnVSlOOMvuZXjhUTObsuZWO8XdgF04CkgZhq94b4Ej__vi4D1mZ2x9zRlrEMA1MEIfV5sN0CAwEAAaOCBAswggQHMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwEwCgYIKwYBBQUHAwIwPQYJKwYBBAGCNxUHBDAwLgYmKwYBBAGCNxUIhpDjDYTVtHiE8Ys-hZvdFs6dEoFggvX2K4Py0SACAWQCAQowggHaBggrBgEFBQcBAQSCAcwwggHIMGYGCCsGAQUFBzAChlpodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpaW5mcmEvQ2VydHMvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmwxLmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MFYGCCsGAQUFBzAChkpodHRwOi8vY3JsMi5hbWUuZ2JsL2FpYS9CTDJQS0lJTlRDQTAxLkFNRS5HQkxfQU1FJTIwSW5mcmElMjBDQSUyMDAyKDQpLmNydDBWBggrBgEFBQcwAoZKaHR0cDovL2NybDMuYW1lLmdibC9haWEvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmw0LmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MB0GA1UdDgQWBBRQX-Vd5gCv8ZxGaXD2PmaqqUHtdjAOBgNVHQ8BAf8EBAMCBaAwggE1BgNVHR8EggEsMIIBKDCCASSgggEgoIIBHIZCaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraWluZnJhL0NSTC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMS5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMi5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMy5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsNC5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JsMBcGA1UdIAQQMA4wDAYKKwYBBAGCN3sBATAfBgNVHSMEGDAWgBSuecJrXSWIEwb2BwnDl3x7l48dVTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAGraIc9hsqUGKcUfGRNlRfK3ussZT-LVHk7wo_N16Hnjq6O3kEOh1mdMNH-uYhMOeqXAg8ua2Co_Ryny1cSbWYBExXVxH2mDnGrRA0cOMEZVd7HGLhG7AvGMFDaxPDge9P_W4kaoMoN3Q3UcKwfZ3H94NyavU0Pk8lqY294YOkd-IgerbhZiIsIR1xE4QglniwVZCNl85WS-QtiJ2urgjIQ6mIdfAQb1mUbHPMh8i3z_av1Wjp5eOUm3MIA7j9kOWVnCEWM_wzDNrLBl-o3cRuUEdVMzmghLEyrN6p0svczMmPBFkSXArQzjyJpTQfM7UHrhAv7N0cUingZ7xJY8z_M&s=KvjeupbGgmQnr0S-w-uRnG8nInZrijZ5tkeghgpWdU5r0UZV9422t7Re0VSNLwl0i9JXYWFg6uA1EF6L0Z90-KJACREMQuPJZJtPyjj6FR9Xc3eFfzB3exvIi88_-13NF6HCPyndKU4TlRCYy8BTsie1g88kp8ZrBGA8tHI16OQag8X6fHP39LTBt-fc8P1goPFoIj-ZZvPgvmnTppwCGo_3EnxHenUmHFSX_Mukrh5SvPQEJC_GIbttLPS6sFWinqvbjp7lr9Xrt1gB1EowoCXA9VCQf3nRwDxFa6LT6RWy-Spb992Mv2uHnzG2Wk0UqDGhvHY5Bt3RKWA3He4rHA&h=SlYQj2yR92-HSIy0FXRCUxOv8fHkj3w-SML6DiHgpew + response: + body: + string: '{"id":"subscriptions/6c933f90-8115-4392-90f2-7077c9fa5dbd/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/default/operationId/3b425f23-04c5-4d40-ad6a-eee9ceabdf5a","name":"3b425f23-04c5-4d40-ad6a-eee9ceabdf5a","status":"Running","startTime":"2023-12-13T04:50:53.4713422Z"}' + headers: + cache-control: + - no-cache + content-length: + - '322' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:50:53 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - '*/*' + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/default/operationId/3b425f23-04c5-4d40-ad6a-eee9ceabdf5a?api-version=2023-11-01-preview&t=638380398536670111&c=MIIHHjCCBgagAwIBAgITfwI8YE7TFpH4swTJAgAEAjxgTjANBgkqhkiG9w0BAQsFADBEMRMwEQYKCZImiZPyLGQBGRYDR0JMMRMwEQYKCZImiZPyLGQBGRYDQU1FMRgwFgYDVQQDEw9BTUUgSW5mcmEgQ0EgMDIwHhcNMjMxMTAxMTI0ODMyWhcNMjQxMDI2MTI0ODMyWjBAMT4wPAYDVQQDEzVhc3luY29wZXJhdGlvbnNpZ25pbmdjZXJ0aWZpY2F0ZS5tYW5hZ2VtZW50LmF6dXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOfk7s1AnKyUqxJR1tGB1o-bd08yXoGVmNHQbpQb9IWlVS7htLxnfaUT083PrTqMEBOB9OS4hyPlFX-ApR1pomKdOD1y0gioSkZG_vgzN2wtFSBJWYWnrCl3xq-Tt9kIsLmZ7FZ-JBOTPKr8rSmKzm4L0NIsVf6UNGZOPdsZpFYEXOeyjshEO6PpPevESOM8rWMDozQTl1HzkC0gPrg5DGhYsJJe5HDWO8h7FZD5HFOCbb225KnGWZppoK08q2QpTgIP8P7CvjQnoGz2CnVSlOOMvuZXjhUTObsuZWO8XdgF04CkgZhq94b4Ej__vi4D1mZ2x9zRlrEMA1MEIfV5sN0CAwEAAaOCBAswggQHMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwEwCgYIKwYBBQUHAwIwPQYJKwYBBAGCNxUHBDAwLgYmKwYBBAGCNxUIhpDjDYTVtHiE8Ys-hZvdFs6dEoFggvX2K4Py0SACAWQCAQowggHaBggrBgEFBQcBAQSCAcwwggHIMGYGCCsGAQUFBzAChlpodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpaW5mcmEvQ2VydHMvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmwxLmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MFYGCCsGAQUFBzAChkpodHRwOi8vY3JsMi5hbWUuZ2JsL2FpYS9CTDJQS0lJTlRDQTAxLkFNRS5HQkxfQU1FJTIwSW5mcmElMjBDQSUyMDAyKDQpLmNydDBWBggrBgEFBQcwAoZKaHR0cDovL2NybDMuYW1lLmdibC9haWEvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmw0LmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MB0GA1UdDgQWBBRQX-Vd5gCv8ZxGaXD2PmaqqUHtdjAOBgNVHQ8BAf8EBAMCBaAwggE1BgNVHR8EggEsMIIBKDCCASSgggEgoIIBHIZCaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraWluZnJhL0NSTC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMS5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMi5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMy5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsNC5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JsMBcGA1UdIAQQMA4wDAYKKwYBBAGCN3sBATAfBgNVHSMEGDAWgBSuecJrXSWIEwb2BwnDl3x7l48dVTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAGraIc9hsqUGKcUfGRNlRfK3ussZT-LVHk7wo_N16Hnjq6O3kEOh1mdMNH-uYhMOeqXAg8ua2Co_Ryny1cSbWYBExXVxH2mDnGrRA0cOMEZVd7HGLhG7AvGMFDaxPDge9P_W4kaoMoN3Q3UcKwfZ3H94NyavU0Pk8lqY294YOkd-IgerbhZiIsIR1xE4QglniwVZCNl85WS-QtiJ2urgjIQ6mIdfAQb1mUbHPMh8i3z_av1Wjp5eOUm3MIA7j9kOWVnCEWM_wzDNrLBl-o3cRuUEdVMzmghLEyrN6p0svczMmPBFkSXArQzjyJpTQfM7UHrhAv7N0cUingZ7xJY8z_M&s=KvjeupbGgmQnr0S-w-uRnG8nInZrijZ5tkeghgpWdU5r0UZV9422t7Re0VSNLwl0i9JXYWFg6uA1EF6L0Z90-KJACREMQuPJZJtPyjj6FR9Xc3eFfzB3exvIi88_-13NF6HCPyndKU4TlRCYy8BTsie1g88kp8ZrBGA8tHI16OQag8X6fHP39LTBt-fc8P1goPFoIj-ZZvPgvmnTppwCGo_3EnxHenUmHFSX_Mukrh5SvPQEJC_GIbttLPS6sFWinqvbjp7lr9Xrt1gB1EowoCXA9VCQf3nRwDxFa6LT6RWy-Spb992Mv2uHnzG2Wk0UqDGhvHY5Bt3RKWA3He4rHA&h=SlYQj2yR92-HSIy0FXRCUxOv8fHkj3w-SML6DiHgpew + response: + body: + string: '{"id":"subscriptions/6c933f90-8115-4392-90f2-7077c9fa5dbd/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/default/operationId/3b425f23-04c5-4d40-ad6a-eee9ceabdf5a","name":"3b425f23-04c5-4d40-ad6a-eee9ceabdf5a","status":"Running","startTime":"2023-12-13T04:50:53.4713422Z"}' + headers: + cache-control: + - no-cache + content-length: + - '322' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:51:03 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - '*/*' + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/default/operationId/3b425f23-04c5-4d40-ad6a-eee9ceabdf5a?api-version=2023-11-01-preview&t=638380398536670111&c=MIIHHjCCBgagAwIBAgITfwI8YE7TFpH4swTJAgAEAjxgTjANBgkqhkiG9w0BAQsFADBEMRMwEQYKCZImiZPyLGQBGRYDR0JMMRMwEQYKCZImiZPyLGQBGRYDQU1FMRgwFgYDVQQDEw9BTUUgSW5mcmEgQ0EgMDIwHhcNMjMxMTAxMTI0ODMyWhcNMjQxMDI2MTI0ODMyWjBAMT4wPAYDVQQDEzVhc3luY29wZXJhdGlvbnNpZ25pbmdjZXJ0aWZpY2F0ZS5tYW5hZ2VtZW50LmF6dXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOfk7s1AnKyUqxJR1tGB1o-bd08yXoGVmNHQbpQb9IWlVS7htLxnfaUT083PrTqMEBOB9OS4hyPlFX-ApR1pomKdOD1y0gioSkZG_vgzN2wtFSBJWYWnrCl3xq-Tt9kIsLmZ7FZ-JBOTPKr8rSmKzm4L0NIsVf6UNGZOPdsZpFYEXOeyjshEO6PpPevESOM8rWMDozQTl1HzkC0gPrg5DGhYsJJe5HDWO8h7FZD5HFOCbb225KnGWZppoK08q2QpTgIP8P7CvjQnoGz2CnVSlOOMvuZXjhUTObsuZWO8XdgF04CkgZhq94b4Ej__vi4D1mZ2x9zRlrEMA1MEIfV5sN0CAwEAAaOCBAswggQHMCcGCSsGAQQBgjcVCgQaMBgwCgYIKwYBBQUHAwEwCgYIKwYBBQUHAwIwPQYJKwYBBAGCNxUHBDAwLgYmKwYBBAGCNxUIhpDjDYTVtHiE8Ys-hZvdFs6dEoFggvX2K4Py0SACAWQCAQowggHaBggrBgEFBQcBAQSCAcwwggHIMGYGCCsGAQUFBzAChlpodHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpaW5mcmEvQ2VydHMvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmwxLmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MFYGCCsGAQUFBzAChkpodHRwOi8vY3JsMi5hbWUuZ2JsL2FpYS9CTDJQS0lJTlRDQTAxLkFNRS5HQkxfQU1FJTIwSW5mcmElMjBDQSUyMDAyKDQpLmNydDBWBggrBgEFBQcwAoZKaHR0cDovL2NybDMuYW1lLmdibC9haWEvQkwyUEtJSU5UQ0EwMS5BTUUuR0JMX0FNRSUyMEluZnJhJTIwQ0ElMjAwMig0KS5jcnQwVgYIKwYBBQUHMAKGSmh0dHA6Ly9jcmw0LmFtZS5nYmwvYWlhL0JMMlBLSUlOVENBMDEuQU1FLkdCTF9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3J0MB0GA1UdDgQWBBRQX-Vd5gCv8ZxGaXD2PmaqqUHtdjAOBgNVHQ8BAf8EBAMCBaAwggE1BgNVHR8EggEsMIIBKDCCASSgggEgoIIBHIZCaHR0cDovL2NybC5taWNyb3NvZnQuY29tL3BraWluZnJhL0NSTC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMS5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMi5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsMy5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JshjRodHRwOi8vY3JsNC5hbWUuZ2JsL2NybC9BTUUlMjBJbmZyYSUyMENBJTIwMDIoNCkuY3JsMBcGA1UdIAQQMA4wDAYKKwYBBAGCN3sBATAfBgNVHSMEGDAWgBSuecJrXSWIEwb2BwnDl3x7l48dVTAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDQYJKoZIhvcNAQELBQADggEBAGraIc9hsqUGKcUfGRNlRfK3ussZT-LVHk7wo_N16Hnjq6O3kEOh1mdMNH-uYhMOeqXAg8ua2Co_Ryny1cSbWYBExXVxH2mDnGrRA0cOMEZVd7HGLhG7AvGMFDaxPDge9P_W4kaoMoN3Q3UcKwfZ3H94NyavU0Pk8lqY294YOkd-IgerbhZiIsIR1xE4QglniwVZCNl85WS-QtiJ2urgjIQ6mIdfAQb1mUbHPMh8i3z_av1Wjp5eOUm3MIA7j9kOWVnCEWM_wzDNrLBl-o3cRuUEdVMzmghLEyrN6p0svczMmPBFkSXArQzjyJpTQfM7UHrhAv7N0cUingZ7xJY8z_M&s=KvjeupbGgmQnr0S-w-uRnG8nInZrijZ5tkeghgpWdU5r0UZV9422t7Re0VSNLwl0i9JXYWFg6uA1EF6L0Z90-KJACREMQuPJZJtPyjj6FR9Xc3eFfzB3exvIi88_-13NF6HCPyndKU4TlRCYy8BTsie1g88kp8ZrBGA8tHI16OQag8X6fHP39LTBt-fc8P1goPFoIj-ZZvPgvmnTppwCGo_3EnxHenUmHFSX_Mukrh5SvPQEJC_GIbttLPS6sFWinqvbjp7lr9Xrt1gB1EowoCXA9VCQf3nRwDxFa6LT6RWy-Spb992Mv2uHnzG2Wk0UqDGhvHY5Bt3RKWA3He4rHA&h=SlYQj2yR92-HSIy0FXRCUxOv8fHkj3w-SML6DiHgpew + response: + body: + string: '{"id":"subscriptions/6c933f90-8115-4392-90f2-7077c9fa5dbd/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/locations/uksouth/operationStatus/default/operationId/3b425f23-04c5-4d40-ad6a-eee9ceabdf5a","name":"3b425f23-04c5-4d40-ad6a-eee9ceabdf5a","status":"Succeeded","startTime":"2023-12-13T04:50:53.4713422Z","endTime":"2023-12-13T04:51:14.3626183Z"}' + headers: + cache-control: + - no-cache + content-length: + - '365' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:51:14 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - '*/*' + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003/deployments/mock-deployment?api-version=2023-11-01-preview + response: + body: + string: '{"properties":{"deploymentSettings":{"resourceRequests":{"cpu":"1","memory":"1Gi"},"environmentVariables":null,"terminationGracePeriodSeconds":90,"livenessProbe":{"disableProbe":false,"failureThreshold":3,"initialDelaySeconds":300,"periodSeconds":10,"successThreshold":1,"timeoutSeconds":3,"probeAction":{"type":"TCPSocketAction"}},"readinessProbe":{"disableProbe":false,"failureThreshold":3,"initialDelaySeconds":0,"periodSeconds":5,"successThreshold":1,"timeoutSeconds":3,"probeAction":{"type":"TCPSocketAction"}}},"provisioningState":"Succeeded","status":"Running","active":true,"instances":[{"name":"clitest000003-default-15-78b7f6c4b7-lm9s8","status":"Running","discoveryStatus":"UNREGISTERED","startTime":"2023-12-13T04:50:58Z"}],"source":{"type":"BuildResult","buildResultId":""}},"type":"Microsoft.AppPlatform/Spring/apps/deployments","sku":{"name":"E0","tier":"Enterprise","capacity":1},"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003/deployments/default","name":"default","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:50:52.8076132Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:50:52.8076132Z"}}' + headers: + cache-control: + - no-cache + content-length: + - '1347' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:51:17 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-resource-requests: + - '11999' + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003?api-version=2023-11-01-preview + response: + body: + string: '{"properties":{"addonConfigs":{"applicationConfigurationService":{"resourceId":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/configurationServices/default"},"serviceRegistry":{"resourceId":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/serviceRegistries/default"}},"public":false,"provisioningState":"Succeeded","fqdn":"clitest000002.azuremicroservices.io","httpsOnly":false,"temporaryDisk":{"sizeInGB":5,"mountPath":"/tmp"},"persistentDisk":{"sizeInGB":0,"mountPath":"/persistent"},"enableEndToEndTLS":false,"ingressSettings":{"readTimeoutInSeconds":300,"sendTimeoutInSeconds":60,"sessionCookieMaxAge":0,"sessionAffinity":"None","backendProtocol":"Default"}},"type":"Microsoft.AppPlatform/Spring/apps","identity":null,"location":"uksouth","id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003","name":"clitest000003","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:50:44.7761384Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:50:44.7761384Z"}}' + headers: + cache-control: + - no-cache + content-length: + - '1351' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:51:25 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-resource-requests: + - '11997' + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +- request: + body: null + headers: + Accept: + - application/json + Accept-Encoding: + - gzip, deflate + CommandName: + - spring app create + Connection: + - keep-alive + ParameterSetName: + - -n -g -s --bind-service-registry --bind-application-configuration-service + User-Agent: + - AZURECLI/2.54.0 azsdk-python-mgmt-appplatform/6.1.0 Python/3.8.10 (Windows-10-10.0.22621-SP0) + method: GET + uri: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003/deployments?api-version=2023-11-01-preview + response: + body: + string: '{"value":[{"properties":{"deploymentSettings":{"resourceRequests":{"cpu":"1","memory":"1Gi"},"environmentVariables":null,"terminationGracePeriodSeconds":90,"livenessProbe":{"disableProbe":false,"failureThreshold":3,"initialDelaySeconds":300,"periodSeconds":10,"successThreshold":1,"timeoutSeconds":3,"probeAction":{"type":"TCPSocketAction"}},"readinessProbe":{"disableProbe":false,"failureThreshold":3,"initialDelaySeconds":0,"periodSeconds":5,"successThreshold":1,"timeoutSeconds":3,"probeAction":{"type":"TCPSocketAction"}}},"provisioningState":"Succeeded","status":"Running","active":true,"instances":[{"name":"clitest000003-default-15-78b7f6c4b7-lm9s8","status":"Running","discoveryStatus":"UNREGISTERED","startTime":"2023-12-13T04:50:58Z"}],"source":{"type":"BuildResult","buildResultId":""}},"type":"Microsoft.AppPlatform/Spring/apps/deployments","sku":{"name":"E0","tier":"Enterprise","capacity":1},"id":"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/clitest.rg000001/providers/Microsoft.AppPlatform/Spring/clitest000002/apps/clitest000003/deployments/default","name":"default","systemData":{"createdBy":"v-shilichen@microsoft.com","createdByType":"User","createdAt":"2023-12-13T04:50:52.8076132Z","lastModifiedBy":"v-shilichen@microsoft.com","lastModifiedByType":"User","lastModifiedAt":"2023-12-13T04:50:52.8076132Z"}}]}' + headers: + cache-control: + - no-cache + content-length: + - '1359' + content-type: + - application/json + date: + - Wed, 13 Dec 2023 04:51:28 GMT + expires: + - '-1' + pragma: + - no-cache + request-context: + - appId=cid-v1:797d7e4e-8180-497e-a254-780fbd39ba4d + strict-transport-security: + - max-age=31536000; includeSubDomains + transfer-encoding: + - chunked + vary: + - Accept-Encoding + x-content-type-options: + - nosniff + x-ms-ratelimit-remaining-subscription-resource-requests: + - '11998' + x-rp-server-mvid: + - fee0e8b1-cd66-4be8-bd08-f7bf9b14616d + status: + code: 200 + message: OK +version: 1 diff --git a/src/spring/azext_spring/tests/latest/test_asa_app.py b/src/spring/azext_spring/tests/latest/test_asa_app.py index 70a8384dba6..d1936136d00 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app.py @@ -714,6 +714,18 @@ def test_app_with_persistent_storage_enterprise(self): with self.assertRaisesRegexp(CLIError, 'Enterprise tier Spring instance does not support --enable-persistent-storage'): self._execute('rg', 'asc', 'app', cpu='500m', memory='2Gi', instance_count=1, enable_persistent_storage=True, client=client) + def test_app_binding_tanzu_components_enterprise(self): + client = self._get_basic_mock_client(sku='Enterprise') + default_service_registry_id = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.AppPlatform/Spring/asa/serviceRegistries/default'; + default_application_configuration_service_id = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.AppPlatform/Spring/asa/configurationServices/default'; + self._execute('rg', 'asc', 'app', cpu='500m', memory='2Gi', instance_count=1, + bind_service_registry=default_service_registry_id, + bind_application_configuration_service=default_application_configuration_service_id, + client=client) + addon_configs = self.put_app_resource.properties.addon_configs + self.assertEqual(default_service_registry_id, addon_configs['serviceRegistry']['resourceId']) + self.assertEqual(default_application_configuration_service_id, addon_configs['applicationConfigurationService']['resourceId']) + def test_app_with_persistent_storage(self): self._execute('rg', 'asc', 'app', cpu='500m', memory='2Gi', instance_count=1, enable_persistent_storage=True) resource = self.put_app_resource diff --git a/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py index dafefe60793..9484b14889d 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py @@ -149,6 +149,27 @@ def test_app_crud_1(self, resource_group, spring, app): self.check('sku.capacity', 1) ]) + @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['resource_group_name']) + @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) + @SpringAppNamePreparer() + def test_app_create_binding_tanzu_components(self, resource_group, spring, app): + self.kwargs.update({ + 'app': app, + 'serviceName': spring, + 'rg': resource_group + }) + + self.cmd('spring app create -n {app} -g {rg} -s {serviceName} \ + --bind-service-registry --bind-application-configuration-service', checks=[ + self.check('name', '{app}'), + self.check('properties.addonConfigs.applicationConfigurationService.resourceId', + "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/configurationServices/default".format( + self.get_subscription_id(), resource_group, spring)), + self.check('properties.addonConfigs.serviceRegistry.resourceId', + "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/serviceRegistries/default".format( + self.get_subscription_id(), resource_group, spring)) + ] + ) class BlueGreenTest(ScenarioTest): diff --git a/src/spring/setup.py b/src/spring/setup.py index 612bf881b25..a066fe56e3a 100644 --- a/src/spring/setup.py +++ b/src/spring/setup.py @@ -16,7 +16,7 @@ # TODO: Confirm this is the right version number you want and it matches your # HISTORY.rst entry. -VERSION = '1.17.0' +VERSION = '1.18.0' # The full list of classifiers is available at # https://pypi.python.org/pypi?%3Aaction=list_classifiers From 0678881b4394fa5bf7371e4425e006227f3f1a64 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Thu, 14 Dec 2023 15:25:48 +0800 Subject: [PATCH 02/19] Format and add short abbreviation --- src/spring/azext_spring/_params.py | 2 ++ .../tests/latest/test_asa_app_scenario.py | 18 +++++++----------- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/src/spring/azext_spring/_params.py b/src/spring/azext_spring/_params.py index 91e5d704511..f9c7230ce0d 100644 --- a/src/spring/azext_spring/_params.py +++ b/src/spring/azext_spring/_params.py @@ -336,10 +336,12 @@ def load_arguments(self, _): help="Space-separated user-assigned managed identity resource IDs to assgin to an app.") c.argument('bind_service_registry', action='store_true', + options_list=['--bind-service-registry', '--bind-sr'], validator=validate_create_app_binding_default_service_registry, help='Bind the app to the default Service Registry automatically.') c.argument('bind_application_configuration_service', action='store_true', + options_list=['--bind-application-configuration-service', '--bind-acs'], validator=validate_create_app_binding_default_application_configuration_service, help='Bind the app to the default Application Configuration Service automatically.') c.argument('cpu', arg_type=cpu_type) diff --git a/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py index 9484b14889d..b584bf9b54d 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py @@ -149,6 +149,7 @@ def test_app_crud_1(self, resource_group, spring, app): self.check('sku.capacity', 1) ]) + @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) @SpringAppNamePreparer() @@ -159,17 +160,12 @@ def test_app_create_binding_tanzu_components(self, resource_group, spring, app): 'rg': resource_group }) - self.cmd('spring app create -n {app} -g {rg} -s {serviceName} \ - --bind-service-registry --bind-application-configuration-service', checks=[ - self.check('name', '{app}'), - self.check('properties.addonConfigs.applicationConfigurationService.resourceId', - "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/configurationServices/default".format( - self.get_subscription_id(), resource_group, spring)), - self.check('properties.addonConfigs.serviceRegistry.resourceId', - "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/serviceRegistries/default".format( - self.get_subscription_id(), resource_group, spring)) - ] - ) + self.cmd('spring app create -n {app} -g {rg} -s {serviceName} --bind-service-registry --bind-application-configuration-service', checks=[ + self.check('name', '{app}'), + self.check('properties.addonConfigs.applicationConfigurationService.resourceId', "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/configurationServices/default".format(self.get_subscription_id(), resource_group, spring)), + self.check('properties.addonConfigs.serviceRegistry.resourceId', "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/serviceRegistries/default".format(self.get_subscription_id(), resource_group, spring)) + ]) + class BlueGreenTest(ScenarioTest): From 594484529e96e08b13550610f284651395e8f535 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Thu, 14 Dec 2023 15:40:52 +0800 Subject: [PATCH 03/19] Format --- src/spring/azext_spring/_validators_enterprise.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/spring/azext_spring/_validators_enterprise.py b/src/spring/azext_spring/_validators_enterprise.py index d057bfbcdd6..36e62222dca 100644 --- a/src/spring/azext_spring/_validators_enterprise.py +++ b/src/spring/azext_spring/_validators_enterprise.py @@ -669,7 +669,9 @@ def validate_create_app_binding_default_service_registry(cmd, namespace): if len(service_registry_resources) > 1: raise ClientRequestError('App cannot bind to multiple service registries.') service_registry_resource = service_registry_resources[0] - normalize_bind_service_registry(namespace, namespace.bind_service_registry, service_registry_resource) + normalize_bind_service_registry(namespace, + namespace.bind_service_registry, + service_registry_resource) def normalize_bind_service_registry(namespace, bind, service_registry_resource): namespace.bind_service_registry = service_registry_resource.id if bind else None @@ -680,11 +682,14 @@ def validate_create_app_binding_default_application_configuration_service(cmd, n client = get_client(cmd) acs_resources = list(client.configuration_services.list(namespace.resource_group, namespace.service)) if len(acs_resources) == 0: - raise ClientRequestError('App cannot bind to application configuration service because it is not configured.') + raise ClientRequestError('App cannot bind to application configuration service ' + 'because it is not configured.') if len(acs_resources) > 1: raise ClientRequestError('App cannot bind to multiple application configuration services.') configuration_service_resource = acs_resources[0] - normalize_bind_application_configuration_service(namespace, namespace.bind_application_configuration_service, configuration_service_resource) + normalize_bind_application_configuration_service(namespace, + namespace.bind_application_configuration_service, + configuration_service_resource) def normalize_bind_application_configuration_service(namespace, bind, configuration_service_resource): namespace.bind_application_configuration_service = configuration_service_resource.id if bind else None From 025f59e44e182e67e956901ee35c7a79a205206a Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Thu, 14 Dec 2023 16:32:07 +0800 Subject: [PATCH 04/19] Format --- src/spring/azext_spring/tests/latest/test_asa_app.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/spring/azext_spring/tests/latest/test_asa_app.py b/src/spring/azext_spring/tests/latest/test_asa_app.py index d1936136d00..84b99240413 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app.py @@ -716,8 +716,8 @@ def test_app_with_persistent_storage_enterprise(self): def test_app_binding_tanzu_components_enterprise(self): client = self._get_basic_mock_client(sku='Enterprise') - default_service_registry_id = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.AppPlatform/Spring/asa/serviceRegistries/default'; - default_application_configuration_service_id = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.AppPlatform/Spring/asa/configurationServices/default'; + default_service_registry_id = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.AppPlatform/Spring/asa/serviceRegistries/default' + default_application_configuration_service_id = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.AppPlatform/Spring/asa/configurationServices/default' self._execute('rg', 'asc', 'app', cpu='500m', memory='2Gi', instance_count=1, bind_service_registry=default_service_registry_id, bind_application_configuration_service=default_application_configuration_service_id, From fbf5ca2d22bc22fa075a682bdbc6f309a9eb1a5b Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 12:36:33 +0800 Subject: [PATCH 05/19] Update src/spring/azext_spring/_validators_enterprise.py Co-authored-by: Yuwei Zhou --- src/spring/azext_spring/_validators_enterprise.py | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/spring/azext_spring/_validators_enterprise.py b/src/spring/azext_spring/_validators_enterprise.py index 36e62222dca..ceb3c4c4efe 100644 --- a/src/spring/azext_spring/_validators_enterprise.py +++ b/src/spring/azext_spring/_validators_enterprise.py @@ -662,16 +662,8 @@ def validate_build_cert_reference(cmd, namespace): def validate_create_app_binding_default_service_registry(cmd, namespace): service_registry_resource = None if namespace.bind_service_registry: - client = get_client(cmd) - service_registry_resources = list(client.service_registries.list(namespace.resource_group, namespace.service)) - if len(service_registry_resources) == 0: - raise ClientRequestError('App cannot bind to service registry because it is not configured.') - if len(service_registry_resources) > 1: - raise ClientRequestError('App cannot bind to multiple service registries.') - service_registry_resource = service_registry_resources[0] - normalize_bind_service_registry(namespace, - namespace.bind_service_registry, - service_registry_resource) + service_registry_resource_id = _get_eactly_one_service_registry_resource_id(cmd, namespace.resource_group, namespace.service) + namespace.bind_service_registry = service_registry_resource_id def normalize_bind_service_registry(namespace, bind, service_registry_resource): namespace.bind_service_registry = service_registry_resource.id if bind else None From 4feb126a7e55e32d2ec49a335beb4f6b226b0680 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 12:36:40 +0800 Subject: [PATCH 06/19] Update src/spring/azext_spring/_app_factory.py Co-authored-by: Yuwei Zhou --- src/spring/azext_spring/_app_factory.py | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/spring/azext_spring/_app_factory.py b/src/spring/azext_spring/_app_factory.py index ccdaaa3ffb4..6186caf4b6b 100644 --- a/src/spring/azext_spring/_app_factory.py +++ b/src/spring/azext_spring/_app_factory.py @@ -181,16 +181,11 @@ def _load_addon_configs(self, bind_service_registry=None, bind_application_confi return None addon_configs = {} - service_registry = {} - application_configuration_service = {} if bind_service_registry: - service_registry['resourceId'] = bind_service_registry + addon_configs['serviceRegistry'] = {'resourceId': bind_service_registry} if bind_application_configuration_service: - application_configuration_service['resourceId'] = bind_application_configuration_service - - addon_configs['serviceRegistry'] = service_registry - addon_configs['applicationConfigurationService'] = application_configuration_service + addon_configs['applicationConfigurationService'] = {'resourceId': bind_application_configuration_service} return addon_configs class BasicTierApp(DefaultApp): From 10c21d9e607fce8807cf470c68238f58ce1620e8 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 14:52:05 +0800 Subject: [PATCH 07/19] Resolve comments --- .../azext_spring/_validators_enterprise.py | 48 +++++++++++-------- 1 file changed, 28 insertions(+), 20 deletions(-) diff --git a/src/spring/azext_spring/_validators_enterprise.py b/src/spring/azext_spring/_validators_enterprise.py index ceb3c4c4efe..d622a873c70 100644 --- a/src/spring/azext_spring/_validators_enterprise.py +++ b/src/spring/azext_spring/_validators_enterprise.py @@ -660,28 +660,36 @@ def validate_build_cert_reference(cmd, namespace): def validate_create_app_binding_default_service_registry(cmd, namespace): - service_registry_resource = None if namespace.bind_service_registry: - service_registry_resource_id = _get_eactly_one_service_registry_resource_id(cmd, namespace.resource_group, namespace.service) - namespace.bind_service_registry = service_registry_resource_id + namespace.bind_service_registry = _get_eactly_one_service_registry_resource_id(cmd, + namespace.resource_group, + namespace.service) + + +def _get_eactly_one_service_registry_resource_id(cmd, resource_group, service): + client = get_client(cmd) + service_registry_resources = list(client.service_registries.list(resource_group, service)) + if len(service_registry_resources) == 0: + raise ClientRequestError('App cannot bind to service registry because it is not configured.') + if len(service_registry_resources) > 1: + raise ClientRequestError('App cannot bind to multiple service registries.') + return service_registry_resources[0].id -def normalize_bind_service_registry(namespace, bind, service_registry_resource): - namespace.bind_service_registry = service_registry_resource.id if bind else None def validate_create_app_binding_default_application_configuration_service(cmd, namespace): - configuration_service_resource = None if namespace.bind_application_configuration_service: - client = get_client(cmd) - acs_resources = list(client.configuration_services.list(namespace.resource_group, namespace.service)) - if len(acs_resources) == 0: - raise ClientRequestError('App cannot bind to application configuration service ' - 'because it is not configured.') - if len(acs_resources) > 1: - raise ClientRequestError('App cannot bind to multiple application configuration services.') - configuration_service_resource = acs_resources[0] - normalize_bind_application_configuration_service(namespace, - namespace.bind_application_configuration_service, - configuration_service_resource) - -def normalize_bind_application_configuration_service(namespace, bind, configuration_service_resource): - namespace.bind_application_configuration_service = configuration_service_resource.id if bind else None + namespace.bind_application_configuration_service \ + = _get_eactly_one_application_configuration_service_resource_id(cmd, + namespace.resource_group, + namespace.service) + + +def _get_eactly_one_application_configuration_service_resource_id(cmd, resource_group, service): + client = get_client(cmd) + acs_resources = list(client.configuration_services.list(resource_group, service)) + if len(acs_resources) == 0: + raise ClientRequestError('App cannot bind to application configuration service ' + 'because it is not configured.') + if len(acs_resources) > 1: + raise ClientRequestError('App cannot bind to multiple application configuration services.') + return acs_resources[0].id From 0c37049cc379f6fd723219d8c577c20799298f76 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 15:38:40 +0800 Subject: [PATCH 08/19] Fix check style errors --- src/spring/azext_spring/_app_factory.py | 5 +- src/spring/azext_spring/_params.py | 2 +- .../azext_spring/tests/latest/test_asa_app.py | 104 +++++++++--------- 3 files changed, 57 insertions(+), 54 deletions(-) diff --git a/src/spring/azext_spring/_app_factory.py b/src/spring/azext_spring/_app_factory.py index 6186caf4b6b..f4199420fd1 100644 --- a/src/spring/azext_spring/_app_factory.py +++ b/src/spring/azext_spring/_app_factory.py @@ -183,11 +183,12 @@ def _load_addon_configs(self, bind_service_registry=None, bind_application_confi addon_configs = {} if bind_service_registry: - addon_configs['serviceRegistry'] = {'resourceId': bind_service_registry} + addon_configs['serviceRegistry'] = {'resourceId': bind_service_registry} if bind_application_configuration_service: - addon_configs['applicationConfigurationService'] = {'resourceId': bind_application_configuration_service} + addon_configs['applicationConfigurationService'] = {'resourceId': bind_application_configuration_service} return addon_configs + class BasicTierApp(DefaultApp): def _get_persistent_disk_size(self, enable_persistent_storage, **_): return 1 if enable_persistent_storage else 0 diff --git a/src/spring/azext_spring/_params.py b/src/spring/azext_spring/_params.py index f9c7230ce0d..8c099ec915a 100644 --- a/src/spring/azext_spring/_params.py +++ b/src/spring/azext_spring/_params.py @@ -284,7 +284,7 @@ def load_arguments(self, _): TestKeyType), help='Type of test-endpoint key') with self.argument_context('spring list-support-server-versions') as c: - c.argument('service', service_name_type, validator=not_support_enterprise) + c.argument('service', service_name_type, validator=not_support_enterprise) with self.argument_context('spring app') as c: c.argument('service', service_name_type) diff --git a/src/spring/azext_spring/tests/latest/test_asa_app.py b/src/spring/azext_spring/tests/latest/test_asa_app.py index 84b99240413..11fdae55ab0 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app.py @@ -255,17 +255,17 @@ def _get_result_resource(self, status='Succeeded'): def _get_build_resource(self): self.result_id = resource_id( - subscription = '00000000-0000-0000-0000-000000000000', - resource_group = 'rg', - name = 'asc', - namespace = 'Microsoft.AppPlatform', + subscription='00000000-0000-0000-0000-000000000000', + resource_group='rg', + name='asc', + namespace='Microsoft.AppPlatform', type='Spring', - child_type_1 = 'buildService', - child_name_1 = 'default', - child_type_2 = 'builds', - child_name_2 = 'builder', - child_type_3 = 'results', - child_name_3 = 'my-result', + child_type_1='buildService', + child_name_1='default', + child_type_2='builds', + child_name_2='builder', + child_type_3='results', + child_name_3='my-result', ) resp = mock.MagicMock() resp.properties.triggered_build_result.id = self.result_id @@ -276,14 +276,14 @@ def _get_upload_info(self): resp.relative_path = 'my-relative-path' resp.upload_url = 'https://mystorage.file.core.windows.net/root/my-relative-path?sv=2018-03-28&sr=f&sig=my-fake-pass&se=2021-12-28T06%3A43%3A17Z&sp=w' return resp - + def verify_build_args(self, client, *args): build_args = client.build_service.create_or_update_build.call_args_list if build_args and build_args[0]: self.assertEqual(1, len(build_args)) self.assertEqual(5, len(build_args[0][0])) - self.assertEqual(args[0:2]+('default',)+(args[2]+'-default',), build_args[0][0][0:4]) + self.assertEqual(args[0:2]+('default',) + (args[2]+'-default',), build_args[0][0][0:4]) self.put_build_resource = build_args[0][0][4] def _execute(self, *args, **kwargs): @@ -314,21 +314,21 @@ def _get_deployment(self): @mock.patch('azext_spring._deployment_uploadable_factory.FileUpload.upload_and_build') def test_app_deploy_enterprise(self, file_mock): file_mock.return_value = mock.MagicMock() - deployment=self._get_deployment() + deployment = self._get_deployment() self._execute('rg', 'asc', 'app', deployment=deployment, artifact_path='my-path', config_file_patterns='my-pattern') resource = self.patch_deployment_resource self.assertEqual('BuildResult', resource.properties.source.type) self.assertEqual(self.result_id, resource.properties.source.build_result_id) self.assertIsNone(resource.properties.source.version) - self.assertEqual({'applicationConfigurationService': {'configFilePatterns': 'my-pattern'}},\ - resource.properties.deployment_settings.addon_configs) + self.assertEqual({'applicationConfigurationService': {'configFilePatterns': 'my-pattern'}}, + resource.properties.deployment_settings.addon_configs) @mock.patch('azext_spring._deployment_uploadable_factory.FileUpload.upload_and_build') def test_app_deploy_build_enterprise(self, file_mock): file_mock.return_value = mock.MagicMock() - deployment=self._get_deployment() + deployment = self._get_deployment() self._execute('rg', 'asc', 'app', deployment=deployment, artifact_path='my-path', - build_env={'BP_JVM_VERSION': '8.*'}, build_cpu='2', build_memory='4Gi') + build_env={'BP_JVM_VERSION': '8.*'}, build_cpu='2', build_memory='4Gi') resource = self.put_build_resource self.assertEqual({"BP_JVM_VERSION": "8.*"}, resource.properties.env) self.assertEqual('2', resource.properties.resource_requests.cpu) @@ -337,7 +337,7 @@ def test_app_deploy_build_enterprise(self, file_mock): @mock.patch('azext_spring._deployment_uploadable_factory.FolderUpload.upload_and_build') def test_app_deploy_folder_enterprise(self, file_mock): file_mock.return_value = mock.MagicMock() - deployment=self._get_deployment() + deployment = self._get_deployment() self._execute('rg', 'asc', 'app', deployment=deployment, source_path='my-path') resource = self.patch_deployment_resource self.assertEqual('BuildResult', resource.properties.source.type) @@ -353,7 +353,7 @@ def test_app_deploy_waiting_enterprise(self, file_mock): self._get_result_resource(status='Building'), self._get_result_resource(status='Succeeded') ] - deployment=self._get_deployment() + deployment = self._get_deployment() self._execute('rg', 'asc', 'app', deployment=deployment, artifact_path='my-path') resource = self.patch_deployment_resource self.assertEqual('BuildResult', resource.properties.source.type) @@ -369,7 +369,7 @@ def test_app_deploy_failed_enterprise(self, file_mock): self._get_result_resource(status='Building'), self._get_result_resource(status='Failed') ] - deployment=self._get_deployment() + deployment = self._get_deployment() with self.assertRaisesRegexp(CLIError, 'Failed to build container image'): self._execute('rg', 'asc', 'app', deployment=deployment, artifact_path='my-path', client=client) @@ -434,7 +434,7 @@ def test_app_deploy_war_from_container(self, file_mock): @mock.patch('azext_spring._deployment_uploadable_factory.FileUpload.upload_and_build') def test_app_deploy_jar_from_container(self, file_mock): file_mock.return_value = mock.MagicMock() - deployment=self._get_deployment() + deployment = self._get_deployment() deployment.properties.source.type = 'Container' deployment.properties.source.custom_container = mock.MagicMock() deployment.properties.source.relative_path = None @@ -475,10 +475,10 @@ def _execute(self, *args, **kwargs): self.assertEqual(4, len(call_args[0][0])) self.assertEqual(args[0:3], call_args[0][0][0:3]) self.patch_app_resource = call_args[0][0][3] - + def test_app_update_without_deployment(self): self._execute('rg', 'asc', 'app', assign_endpoint=True) - + self.assertIsNone(self.patch_deployment_resource) resource = self.patch_app_resource self.assertEqual(True, resource.properties.public) @@ -486,7 +486,7 @@ def test_app_update_without_deployment(self): def test_invalid_app_update_deployment_settings_without_deployment(self): with self.assertRaisesRegexp(CLIError, '--jvm-options cannot be set when there is no active deployment.'): self._execute('rg', 'asc', 'app', jvm_options='test-option') - + def test_app_update_jvm_options(self): self._execute('rg', 'asc', 'app', deployment=self._get_deployment(), jvm_options='test-option') resource = self.patch_deployment_resource @@ -503,7 +503,7 @@ def test_app_set_termination_grace_period_seconds(self): def test_app_disable_probes(self): self._execute('rg', 'asc', 'app', deployment=self._get_deployment(), enable_liveness_probe=False, - enable_readiness_probe=False, enable_startup_probe=False) + enable_readiness_probe=False, enable_startup_probe=False) resource = self.patch_deployment_resource self.assertEqual(True, resource.properties.deployment_settings.liveness_probe.disable_probe) self.assertEqual(True, resource.properties.deployment_settings.readiness_probe.disable_probe) @@ -511,9 +511,9 @@ def test_app_disable_probes(self): def test_app_enable_probe(self): py_path = os.path.abspath(os.path.dirname(__file__)) - file_path = os.path.join(py_path, 'files/probe.json').replace("\\","/") + file_path = os.path.join(py_path, 'files/probe.json').replace("\\", "/") self._execute('rg', 'asc', 'app', deployment=self._get_deployment(), enable_liveness_probe=True, - liveness_probe_config=file_path) + liveness_probe_config=file_path) resource = self.patch_deployment_resource self.assertEqual(False, resource.properties.deployment_settings.liveness_probe.disable_probe) self.assertEqual(30, resource.properties.deployment_settings.liveness_probe.initial_delay_seconds) @@ -523,7 +523,7 @@ def test_app_enable_probe(self): self.assertEqual(30, resource.properties.deployment_settings.liveness_probe.failure_threshold) def test_app_update_net_core_main_entry(self): - deployment=self._get_deployment() + deployment = self._get_deployment() deployment.properties.source.type = 'NetCoreZip' deployment.properties.source.runtime_version = 'NetCore_31' deployment.properties.source.net_core_main_entry_path = 'main-entry' @@ -536,24 +536,24 @@ def test_app_update_net_core_main_entry(self): self.assertEqual('test-entry', resource.properties.source.net_core_main_entry_path) def test_app_update_settings_only(self): - deployment=self._get_deployment() - self._execute('rg', 'asc', 'app', deployment=deployment, env={'key':'value'}) + deployment = self._get_deployment() + self._execute('rg', 'asc', 'app', deployment=deployment, env={'key': 'value'}) resource = self.patch_deployment_resource self.assertIsNone(resource.properties.source) - self.assertEqual({'key':'value'}, resource.properties.deployment_settings.environment_variables) + self.assertEqual({'key': 'value'}, resource.properties.deployment_settings.environment_variables) def test_app_update_in_enterprise(self): client = self._get_basic_mock_client(sku='Enterprise') - deployment=self._get_deployment(sku='Enterprise') + deployment = self._get_deployment(sku='Enterprise') deployment.properties.deployment_settings.addon_configs = {'applicationConfigurationService': {'configFilePatterns': 'my-pattern'}} self._execute('rg', 'asc', 'app', deployment=deployment, client=client, config_file_patterns='updated-pattern') resource = self.patch_deployment_resource - self.assertEqual({'applicationConfigurationService': {'configFilePatterns': 'updated-pattern'}},\ + self.assertEqual({'applicationConfigurationService': {'configFilePatterns': 'updated-pattern'}}, resource.properties.deployment_settings.addon_configs) def test_app_update_clear_jvm_option_in_enterprise(self): client = self._get_basic_mock_client(sku='Enterprise') - deployment=self._get_deployment(sku='Enterprise') + deployment = self._get_deployment(sku='Enterprise') deployment.properties.deployment_settings.environment_variables = {"JAVA_OPTS": "test_options", "foo": "bar"} self._execute('rg', 'asc', 'app', deployment=deployment, client=client, jvm_options='') resource = self.patch_deployment_resource @@ -561,7 +561,7 @@ def test_app_update_clear_jvm_option_in_enterprise(self): def test_app_update_in_enterprise_with_new_set_env(self): client = self._get_basic_mock_client(sku='Enterprise') - deployment=self._get_deployment(sku='Enterprise') + deployment = self._get_deployment(sku='Enterprise') deployment.properties.deployment_settings.environment_variables = {"JAVA_OPTS": "test_options", "foo": "bar"} self._execute('rg', 'asc', 'app', deployment=deployment, client=client, env={'key': 'value'}) resource = self.patch_deployment_resource @@ -569,32 +569,32 @@ def test_app_update_in_enterprise_with_new_set_env(self): def test_app_update_env_and_jvm_in_enterprise(self): client = self._get_basic_mock_client(sku='Enterprise') - deployment=self._get_deployment(sku='Enterprise') + deployment = self._get_deployment(sku='Enterprise') deployment.properties.deployment_settings.environment_variables = {"JAVA_OPTS": "test_options", "foo": "bar"} self._execute('rg', 'asc', 'app', deployment=deployment, client=client, jvm_options='another-option', env={'key': 'value'}) resource = self.patch_deployment_resource self.assertEqual({'JAVA_OPTS': 'another-option', 'key': 'value'}, resource.properties.deployment_settings.environment_variables) def test_app_update_custom_container_deployment(self): - deployment=self._get_deployment() + deployment = self._get_deployment() deployment.properties.source.type = 'Container' deployment.properties.source.custom_container.container_image = 'my-image' self._execute('rg', 'asc', 'app', deployment=deployment, env={'key':'value'}) resource = self.patch_deployment_resource self.assertIsNone(resource.properties.source) - self.assertEqual({'key':'value'}, resource.properties.deployment_settings.environment_variables) + self.assertEqual({'key': 'value'}, resource.properties.deployment_settings.environment_variables) def test_app_update_custom_container_deployment_with_invalid_source(self): - deployment=self._get_deployment() + deployment = self._get_deployment() deployment.properties.source.type = 'Container' deployment.properties.source.custom_container.container_image = 'my-image' - self._execute('rg', 'asc', 'app', deployment=deployment, env={'key':'value'}, runtime_version='Java_11') + self._execute('rg', 'asc', 'app', deployment=deployment, env={'key': 'value'}, runtime_version='Java_11') resource = self.patch_deployment_resource self.assertIsNone(resource.properties.source) - self.assertEqual({'key':'value'}, resource.properties.deployment_settings.environment_variables) + self.assertEqual({'key': 'value'}, resource.properties.deployment_settings.environment_variables) def test_steeltoe_app_cannot_set_jvm_options(self): - deployment=self._get_deployment() + deployment = self._get_deployment() deployment.properties.source.type = 'NetCoreZip' deployment.properties.source.runtime_version = 'NetCore_31' deployment.properties.source.net_core_main_entry_path = 'main-entry' @@ -611,11 +611,11 @@ def test_vnet_public_endpoint(self): self._execute('rg', 'asc', 'app', deployment=deployment) resource = self.patch_app_resource self.assertIsNone(resource.properties.vnet_addons) - + self._execute('rg', 'asc', 'app', assign_public_endpoint=False, deployment=deployment) resource = self.patch_app_resource self.assertFalse(resource.properties.vnet_addons.public_endpoint) - + def test_client_auth(self): deployment = self._get_deployment() self._execute('rg', 'asc', 'app', client_auth_certs=['my-cert-id'], deployment=deployment) @@ -632,16 +632,17 @@ def test_app_i2a_tls(self): self._execute('rg', 'asc', 'app', deployment=deployment) resource = self.patch_app_resource self.assertIsNone(resource.properties.enable_end_to_end_tls) - + self._execute('rg', 'asc', 'app', enable_ingress_to_app_tls=False, deployment=deployment) resource = self.patch_app_resource - self.assertFalse(resource.properties.enable_end_to_end_tls) + self.assertFalse(resource.properties.enable_end_to_end_tls) def test_update_workload_profile(self): self._execute('rg', 'asc', 'app', workload_profile='w2') resource = self.patch_app_resource self.assertEqual('w2', resource.properties.workload_profile_name) + class TestAppCreate(BasicTest): def __init__(self, methodName: str = ...): super().__init__(methodName=methodName) @@ -741,7 +742,7 @@ def test_app_with_assign_public_endpoint(self): self._execute('rg', 'asc', 'app', cpu='500m', memory='2Gi', instance_count=1, assign_public_endpoint=True) resource = self.put_app_resource self.assertEqual(True, resource.properties.vnet_addons.public_endpoint) - + def test_app_with_ingress_settings(self): self._execute('rg', 'asc', 'app', instance_count=1, ingress_read_timeout=600, ingress_send_timeout=1200, session_affinity='Cookie', session_max_age=1000, backend_protocol='Default') @@ -788,6 +789,7 @@ def test_create_with_workload_profile(self): resource = self.put_app_resource self.assertEqual('w1', resource.properties.workload_profile_name) + class TestDeploymentCreate(BasicTest): def __init__(self, methodName: str = ...): super().__init__(methodName=methodName) @@ -830,7 +832,7 @@ def test_create_deployment_with_active(self): self.assertEqual('Java_11', resource.properties.source.runtime_version) self.assertEqual('', resource.properties.source.relative_path) self.assertEqual('Jar', resource.properties.source.type) - + def test_create_deployment_with_active_override(self): deployment = self._get_deployment() deployment.properties.active = True @@ -844,7 +846,7 @@ def test_create_deployment_with_active_override(self): self.assertEqual('NetCoreZip', resource.properties.source.type) self.assertEqual('NetCore_31', resource.properties.source.runtime_version) self.assertEqual('', resource.properties.source.relative_path) - + def test_create_deployment_with_active_is_source(self): deployment = self._get_deployment() deployment.properties.active = True @@ -859,7 +861,7 @@ def test_create_deployment_with_active_is_source(self): self.assertEqual('Jar', resource.properties.source.type) self.assertEqual('Java_11', resource.properties.source.runtime_version) self.assertEqual('', resource.properties.source.relative_path) - + def test_create_deployment_with_active_is_container(self): deployment = self._get_deployment() deployment.properties.active = True @@ -881,7 +883,7 @@ def test_create_deployment_with_ACS_Pattern_in_enterprise(self): deployment.properties.deployment_settings.addon_configs = {'applicationConfigurationService': {'configFilePatterns': 'my-pattern'}} self._execute('rg', 'asc', 'app', 'green', client=client) resource = self.put_deployment_resource - self.assertEqual({'applicationConfigurationService': {'configFilePatterns': 'my-pattern'}},\ + self.assertEqual({'applicationConfigurationService': {'configFilePatterns': 'my-pattern'}}, resource.properties.deployment_settings.addon_configs) From d01ad93d519c79b322a8e91158f4932f655e2a61 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 15:55:37 +0800 Subject: [PATCH 09/19] Fix check style errors --- .../azext_spring/tests/latest/test_asa_app.py | 15 ++++++++------- .../tests/latest/test_asa_app_scenario.py | 6 +----- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/src/spring/azext_spring/tests/latest/test_asa_app.py b/src/spring/azext_spring/tests/latest/test_asa_app.py index 11fdae55ab0..a61b44092c1 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app.py @@ -29,6 +29,7 @@ logger = get_logger(__name__) TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + def _get_test_cmd(): cli_ctx = DummyCli() cli_ctx.data['subscription_id'] = '00000000-0000-0000-0000-000000000000' @@ -192,7 +193,7 @@ def test_app_deploy_net_with_jvm_options(self, file_mock): @mock.patch('azext_spring._deployment_uploadable_factory.FileUpload.upload_and_build') def test_app_continous_deploy_net(self, file_mock): file_mock.return_value = mock.MagicMock() - deployment=self._get_deployment() + deployment = self._get_deployment() deployment.properties.source.type = 'NetCoreZip' deployment.properties.source.relative_path = 'my-path' deployment.properties.source.runtime_version = 'NetCore_31' @@ -219,7 +220,7 @@ def test_app_deploy_source(self, file_mock): @mock.patch('azext_spring._deployment_uploadable_factory.FolderUpload.upload_and_build') def test_app_continous_deploy_source(self, file_mock): file_mock.return_value = mock.MagicMock() - deployment=self._get_deployment() + deployment = self._get_deployment() deployment.properties.source.type = 'Container' deployment.properties.source.relative_path = 'my-path' deployment.properties.source.version = '123' @@ -283,7 +284,7 @@ def verify_build_args(self, client, *args): if build_args and build_args[0]: self.assertEqual(1, len(build_args)) self.assertEqual(5, len(build_args[0][0])) - self.assertEqual(args[0:2]+('default',) + (args[2]+'-default',), build_args[0][0][0:4]) + self.assertEqual(args[0:2] + ('default',) + (args[2] + '-default',), build_args[0][0][0:4]) self.put_build_resource = build_args[0][0][4] def _execute(self, *args, **kwargs): @@ -297,7 +298,7 @@ def _execute(self, *args, **kwargs): self.assertEqual(5, len(call_args[0][0])) self.assertEqual(args[0:3] + ('default',), call_args[0][0][0:4]) self.patch_deployment_resource = call_args[0][0][4] - + def _get_deployment(self): deployment = super()._get_deployment() deployment.properties.source.type = 'BuildResult' @@ -600,7 +601,7 @@ def test_steeltoe_app_cannot_set_jvm_options(self): deployment.properties.source.net_core_main_entry_path = 'main-entry' with self.assertRaisesRegexp(CLIError, '--jvm-options cannot be set when --runtime-version is NetCore_31.'): self._execute('rg', 'asc', 'app', jvm_options='test-option', deployment=deployment) - + def test_vnet_public_endpoint(self): deployment = self._get_deployment() @@ -744,7 +745,7 @@ def test_app_with_assign_public_endpoint(self): self.assertEqual(True, resource.properties.vnet_addons.public_endpoint) def test_app_with_ingress_settings(self): - self._execute('rg', 'asc', 'app', instance_count=1, ingress_read_timeout=600, ingress_send_timeout=1200, session_affinity='Cookie', + self._execute('rg', 'asc', 'app', instance_count=1, ingress_read_timeout=600, ingress_send_timeout=1200, session_affinity='Cookie', session_max_age=1000, backend_protocol='Default') resource = self.put_app_resource self.assertEqual(600, resource.properties.ingress_settings.read_timeout_in_seconds) @@ -878,7 +879,7 @@ def test_create_deployment_with_active_is_container(self): self.assertEqual('', resource.properties.source.relative_path) def test_create_deployment_with_ACS_Pattern_in_enterprise(self): - deployment=self._get_deployment(sku='Enterprise') + deployment = self._get_deployment(sku='Enterprise') client = self._get_basic_mock_client('Enterprise', deployment) deployment.properties.deployment_settings.addon_configs = {'applicationConfigurationService': {'configFilePatterns': 'my-pattern'}} self._execute('rg', 'asc', 'app', 'green', client=client) diff --git a/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py index b584bf9b54d..c4890ce0589 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py @@ -51,13 +51,12 @@ def test_deploy_app(self, resource_group, spring, app): with self.assertRaisesRegexp(CLIError, "112404: Exit code 1: application error."): self.cmd('spring app deploy -n {app} -g {rg} -s {serviceName} --artifact-path {file} --version v1') - @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.STANDARD['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.STANDARD['spring']) @SpringAppNamePreparer() def test_deploy_app_1(self, resource_group, spring, app): py_path = os.path.abspath(os.path.dirname(__file__)) - file_path = os.path.join(py_path, 'files/test.jar').replace("\\","/") + file_path = os.path.join(py_path, 'files/test.jar').replace("\\", "/") self.kwargs.update({ 'app': app, 'serviceName': spring, @@ -122,7 +121,6 @@ def test_app_crud(self, resource_group, spring, app): self.check('properties.deploymentSettings.environmentVariables', {'foo': 'bar'}), ]) - @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.STANDARD['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.STANDARD['spring']) @SpringAppNamePreparer() @@ -149,7 +147,6 @@ def test_app_crud_1(self, resource_group, spring, app): self.check('sku.capacity', 1) ]) - @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) @SpringAppNamePreparer() @@ -243,7 +240,6 @@ def test_app_deploy_container(self, resource_group, spring, app): self.check('properties.source.customContainer.languageFramework', None), ]) - @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.STANDARD['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.STANDARD['spring']) @SpringAppNamePreparer() From da75129c8d3fbccc937d98ecd6cfe98ff865e863 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 16:16:08 +0800 Subject: [PATCH 10/19] Fix check style errors --- src/spring/azext_spring/_app_validator.py | 6 +- .../test_app_managed_identity_scenario.py | 16 ++-- .../tests/latest/test_asa_api_portal.py | 22 +++--- ...t_asa_application_configuration_service.py | 16 ++-- .../tests/latest/test_asa_gateway.py | 76 ++++++++++--------- 5 files changed, 73 insertions(+), 63 deletions(-) diff --git a/src/spring/azext_spring/_app_validator.py b/src/spring/azext_spring/_app_validator.py index 47ff40c36d0..53913dd96f1 100644 --- a/src/spring/azext_spring/_app_validator.py +++ b/src/spring/azext_spring/_app_validator.py @@ -159,6 +159,6 @@ def _validate_container_registry(cmd, namespace): " See more details in https://learn.microsoft.com/en-us/azure/spring-apps/how-to-deploy-with-custom-container-image?tabs=azure-cli") except ResourceNotFoundError: if namespace.source_path or namespace.artifact_path: - raise InvalidArgumentValueError( - "The instance without build service can only use '--container-image' to deploy." - " See more details in https://learn.microsoft.com/en-us/azure/spring-apps/how-to-deploy-with-custom-container-image?tabs=azure-cli") + raise InvalidArgumentValueError( + "The instance without build service can only use '--container-image' to deploy." + " See more details in https://learn.microsoft.com/en-us/azure/spring-apps/how-to-deploy-with-custom-container-image?tabs=azure-cli") diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py index 82c99b741cd..4606c44be34 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py @@ -79,20 +79,20 @@ def test_app_identity_crud(self): self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) self.cmd('spring app identity remove -n {app} -g {rg} -s {serviceName} --user-assigned {ua2}',checks=[ - self.check('identity.type', ManagedIdentityType.SYSTEM_ASSIGNED, case_sensitive=False), - self.exists('identity.tenantId'), - self.exists('identity.principalId'), - self.check('identity.userAssignedIdentities', None) + self.check('identity.type', ManagedIdentityType.SYSTEM_ASSIGNED, case_sensitive=False), + self.exists('identity.tenantId'), + self.exists('identity.principalId'), + self.check('identity.userAssignedIdentities', None) ]) self.cmd('spring app identity remove -n {app} -g {rg} -s {serviceName} --system-assigned', checks=[self.check('identity', None)]) app = self.cmd('spring app identity assign -n {app} -g {rg} -s {serviceName} --system-assigned --user-assigned {ua1} {ua2}', checks=[ - self.check('identity.type', ManagedIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, case_sensitive=False), - self.exists('identity.tenantId'), - self.exists('identity.principalId'), - self.exists('identity.userAssignedIdentities') + self.check('identity.type', ManagedIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED, case_sensitive=False), + self.exists('identity.tenantId'), + self.exists('identity.principalId'), + self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) self.assertTrue(type(user_identity_dict) == dict) diff --git a/src/spring/azext_spring/tests/latest/test_asa_api_portal.py b/src/spring/azext_spring/tests/latest/test_asa_api_portal.py index 5adbd08f396..a0d0786ba8c 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_api_portal.py +++ b/src/spring/azext_spring/tests/latest/test_asa_api_portal.py @@ -66,16 +66,18 @@ def test_api_portal(self, resource_group, spring, sp_name, sp_password): self.cmd('spring api-portal update -g {rg} -s {serviceName} ' '--assign-endpoint true --https-only true --instance-count 1 ' - '--client-id {clientId} --client-secret {secret} --issuer-uri https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0 --scope "openid,profile,email"', checks=[ - self.check('properties.public', True), - self.check('properties.httpsOnly', True), - self.check('sku.capacity', 1), - self.check('properties.ssoProperties.clientId', "*"), - self.check('properties.ssoProperties.clientSecret', "*"), - self.check('properties.ssoProperties.issuerUri', "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0"), - self.check('properties.ssoProperties.scope', ["openid", "profile", "email"]), - self.check('properties.provisioningState', "Succeeded") - ]) + '--client-id {clientId} --client-secret {secret} --issuer-uri https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0 --scope "openid,profile,email"', + checks=[ + self.check('properties.public', True), + self.check('properties.httpsOnly', True), + self.check('sku.capacity', 1), + self.check('properties.ssoProperties.clientId', "*"), + self.check('properties.ssoProperties.clientSecret', "*"), + self.check('properties.ssoProperties.issuerUri', "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0"), + self.check('properties.ssoProperties.scope', ["openid", "profile", "email"]), + self.check('properties.provisioningState', "Succeeded") + ] + ) self.cmd('spring api-portal show -g {rg} -s {serviceName}', checks=[ self.check('properties.public', True), diff --git a/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py b/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py index 76fe4ea4cd1..6ed4323dc0c 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py +++ b/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py @@ -56,14 +56,18 @@ def test_application_configuration_service(self, resource_group, spring, app): ]) self.cmd('spring application-configuration-service git repo add -g {rg} -s {serviceName} ' - '-n {repo} --label {label} --patterns {patterns} --uri {uri}', checks=[ - self.check('properties.provisioningState', "Succeeded") - ]) + '-n {repo} --label {label} --patterns {patterns} --uri {uri}', + checks=[ + self.check('properties.provisioningState', "Succeeded") + ] + ) self.cmd('spring application-configuration-service git repo update -g {rg} -s {serviceName} ' - '-n {repo} --label {label}', checks=[ - self.check('properties.provisioningState', "Succeeded") - ]) + '-n {repo} --label {label}', + checks=[ + self.check('properties.provisioningState', "Succeeded") + ] + ) result = self.cmd('spring application-configuration-service git repo list -g {rg} -s {serviceName}').get_output_in_json() self.assertTrue(len(result) > 0) diff --git a/src/spring/azext_spring/tests/latest/test_asa_gateway.py b/src/spring/azext_spring/tests/latest/test_asa_gateway.py index 375492d56d3..d1edc1da88a 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_gateway.py +++ b/src/spring/azext_spring/tests/latest/test_asa_gateway.py @@ -39,44 +39,48 @@ def test_gateway(self): '--apm-types NewRelic ElasticAPM --properties a=b c=d --secrets e=f g=h ' '--allowed-origins "*" --allowed-origin-patterns "example*" --allowed-methods "GET,PUT,DELETE" --allowed-headers "X-TEST,X-STAGING" --max-age 10 --allow-credentials true --exposed-headers "Access-Control-Request-Method,Access-Control-Request-Headers" ' '--client-id * --client-secret * --issuer-uri https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0 --scope "openid,profile,email" ' - '--addon-configs-file {addonConfigsFile}', checks=[ - self.check('properties.public', True), - self.check('properties.httpsOnly', True), - self.check('properties.resourceRequests.cpu', "1"), - self.check('properties.resourceRequests.memory', "2Gi"), - self.check('sku.capacity', 3), - self.check('properties.operatorProperties.resourceRequests.cpu', "1"), - self.check('properties.operatorProperties.resourceRequests.memory', "2Gi"), - self.check('properties.operatorProperties.resourceRequests.instanceCount', 1), - self.check('properties.apiMetadataProperties.title', "Pet clinic"), - self.check('properties.apiMetadataProperties.description', "Demo for pet clinic"), - self.check('properties.apiMetadataProperties.documentation', "doc"), - self.check('properties.apiMetadataProperties.serverUrl', "https://tx-enterprise-gateway-fd0c7.svc.asc-test.net"), - self.check('properties.apiMetadataProperties.version', "v1"), - self.check('properties.corsProperties.allowCredentials', True), - self.check('properties.corsProperties.allowedHeaders', ["X-TEST", "X-STAGING"]), - self.check('properties.corsProperties.allowedOrigins', ["*"]), - self.check('properties.corsProperties.allowedOriginPatterns', ["example*"]), - self.check('properties.corsProperties.allowedMethods', ["GET", "PUT", "DELETE"]), - self.check('properties.corsProperties.exposedHeaders', ["Access-Control-Request-Method", "Access-Control-Request-Headers"]), - self.check('properties.ssoProperties.clientId', "*"), - self.check('properties.ssoProperties.clientSecret', "*"), - self.check('properties.ssoProperties.issuerUri', "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0"), - self.check('properties.ssoProperties.scope', ["openid", "profile", "email"]), - self.check('properties.clientAuth.certificates', ["/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/certificates/abc"]), - self.check('properties.clientAuth.certificateVerification', "Enabled"), - self.check('properties.apmTypes', ["NewRelic", "ElasticAPM"]), - self.check('properties.environmentVariables.properties', {'a': 'b', 'c': 'd'}), - self.check('properties.environmentVariables.secrets', None), - self.check('properties.addonConfigs', {'javaOpts':'-Djava.awt.headless=true','sso':{'rolesAttributeName':'role','inactiveSessionExpirationInMinutes':1},'envs':[{'name':'xxx','value':'yyy'},{'name':'xxx1','value':'yyy'}]}), - self.check('properties.provisioningState', "Succeeded") - ]) + '--addon-configs-file {addonConfigsFile}', + checks=[ + self.check('properties.public', True), + self.check('properties.httpsOnly', True), + self.check('properties.resourceRequests.cpu', "1"), + self.check('properties.resourceRequests.memory', "2Gi"), + self.check('sku.capacity', 3), + self.check('properties.operatorProperties.resourceRequests.cpu', "1"), + self.check('properties.operatorProperties.resourceRequests.memory', "2Gi"), + self.check('properties.operatorProperties.resourceRequests.instanceCount', 1), + self.check('properties.apiMetadataProperties.title', "Pet clinic"), + self.check('properties.apiMetadataProperties.description', "Demo for pet clinic"), + self.check('properties.apiMetadataProperties.documentation', "doc"), + self.check('properties.apiMetadataProperties.serverUrl', "https://tx-enterprise-gateway-fd0c7.svc.asc-test.net"), + self.check('properties.apiMetadataProperties.version', "v1"), + self.check('properties.corsProperties.allowCredentials', True), + self.check('properties.corsProperties.allowedHeaders', ["X-TEST", "X-STAGING"]), + self.check('properties.corsProperties.allowedOrigins', ["*"]), + self.check('properties.corsProperties.allowedOriginPatterns', ["example*"]), + self.check('properties.corsProperties.allowedMethods', ["GET", "PUT", "DELETE"]), + self.check('properties.corsProperties.exposedHeaders', ["Access-Control-Request-Method", "Access-Control-Request-Headers"]), + self.check('properties.ssoProperties.clientId', "*"), + self.check('properties.ssoProperties.clientSecret', "*"), + self.check('properties.ssoProperties.issuerUri', "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0"), + self.check('properties.ssoProperties.scope', ["openid", "profile", "email"]), + self.check('properties.clientAuth.certificates', ["/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/certificates/abc"]), + self.check('properties.clientAuth.certificateVerification', "Enabled"), + self.check('properties.apmTypes', ["NewRelic", "ElasticAPM"]), + self.check('properties.environmentVariables.properties', {'a': 'b', 'c': 'd'}), + self.check('properties.environmentVariables.secrets', None), + self.check('properties.addonConfigs', {'javaOpts':'-Djava.awt.headless=true','sso':{'rolesAttributeName':'role','inactiveSessionExpirationInMinutes':1},'envs':[{'name':'xxx','value':'yyy'},{'name':'xxx1','value':'yyy'}]}), + self.check('properties.provisioningState', "Succeeded") + ] + ) self.cmd('spring gateway update -g {rg} -s {serviceName} ' - '--apm-types '' --apms test-ai', checks=[ - self.check('properties.apms', [{'resourceId': '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apms/test-ai'}]), - self.check('properties.provisioningState', "Succeeded") - ]) + '--apm-types '' --apms test-ai', + checks=[ + self.check('properties.apms', [{'resourceId': '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apms/test-ai'}]), + self.check('properties.provisioningState', "Succeeded") + ] + ) self.cmd('spring gateway show -g {rg} -s {serviceName}', checks=[ self.check('properties.public', True), From fdc33fb9da13b23522feda54cb67dcc7f92bfc55 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 16:37:34 +0800 Subject: [PATCH 11/19] Fix check style errors --- .../tests/latest/test_asa_api_portal.py | 4 +-- .../latest/test_asa_api_portal_try_out_api.py | 1 - .../tests/latest/test_asa_app_validator.py | 8 ++--- .../test_asa_application_accelerator.py | 9 +++--- .../tests/latest/test_asa_create.py | 6 ++-- .../tests/latest/test_asa_gateway.py | 32 +++++++++++-------- .../latest/test_asa_gateway_response_cache.py | 12 +++---- .../latest/test_asa_gateway_validator.py | 9 +++--- .../tests/latest/test_asa_scenario.py | 14 ++++---- .../tests/latest/test_asa_service_registry.py | 6 ++-- .../tests/latest/test_asa_update.py | 1 + .../tests/latest/test_asa_validator.py | 6 +++- 12 files changed, 61 insertions(+), 47 deletions(-) diff --git a/src/spring/azext_spring/tests/latest/test_asa_api_portal.py b/src/spring/azext_spring/tests/latest/test_asa_api_portal.py index a0d0786ba8c..bc271155804 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_api_portal.py +++ b/src/spring/azext_spring/tests/latest/test_asa_api_portal.py @@ -76,8 +76,8 @@ def test_api_portal(self, resource_group, spring, sp_name, sp_password): self.check('properties.ssoProperties.issuerUri', "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0"), self.check('properties.ssoProperties.scope', ["openid", "profile", "email"]), self.check('properties.provisioningState', "Succeeded") - ] - ) + ] + ) self.cmd('spring api-portal show -g {rg} -s {serviceName}', checks=[ self.check('properties.public', True), diff --git a/src/spring/azext_spring/tests/latest/test_asa_api_portal_try_out_api.py b/src/spring/azext_spring/tests/latest/test_asa_api_portal_try_out_api.py index ecdb241a658..f22251a842c 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_api_portal_try_out_api.py +++ b/src/spring/azext_spring/tests/latest/test_asa_api_portal_try_out_api.py @@ -34,4 +34,3 @@ def test_try_out_api_for_api_portal(self): self.cmd('spring api-portal update -g {rg} -s {serviceName} --enable-api-try-out true', self.check('properties.apiTryOutEnabledState', 'Enabled')) - diff --git a/src/spring/azext_spring/tests/latest/test_asa_app_validator.py b/src/spring/azext_spring/tests/latest/test_asa_app_validator.py index 549921d4983..021fedd876f 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app_validator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app_validator.py @@ -172,7 +172,7 @@ def test_deployment_provide(self, client_factory_mock): ns = Namespace(name='app1', service='asc1', resource_group='rg1', deployment='green1') fulfill_deployment_param(_get_test_cmd(), ns) self.assertEqual('/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.AppPlatform/Spring/asc1/apps/app1/deployments/green1', - ns.deployment.id) + ns.deployment.id) self.assertFalse(ns.deployment.properties.active) @@ -202,7 +202,7 @@ def test_deployment_with_active_deployment(self, client_factory_mock): ns = Namespace(name='app1', service='asc1', resource_group='rg1', deployment=None) fulfill_deployment_param(_get_test_cmd(), ns) self.assertEqual('/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.AppPlatform/Spring/asc1/apps/app1/deployments/default', - ns.deployment.id) + ns.deployment.id) self.assertTrue(ns.deployment.properties.active) @mock.patch('azext_spring._app_validator.cf_spring', autospec=True) @@ -217,7 +217,7 @@ def test_deployment_with_active_deployment_for_app_parameter(self, client_factor ns = Namespace(app='app1', service='asc1', resource_group='rg1', deployment=None) fulfill_deployment_param(_get_test_cmd(), ns) self.assertEqual('/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg1/providers/Microsoft.AppPlatform/Spring/asc1/apps/app1/deployments/default', - ns.deployment.id) + ns.deployment.id) self.assertTrue(ns.deployment.properties.active) @mock.patch('azext_spring._app_validator.cf_spring', autospec=True) @@ -242,4 +242,4 @@ def test_deployment_without_deployment(self, client_factory_mock): ns = Namespace(name='app1', service='asc1', resource_group='rg1', deployment=None) with self.assertRaises(InvalidArgumentValueError) as context: fulfill_deployment_param(_get_test_cmd(), ns) - self.assertEqual('No production deployment found, use --deployment to specify deployment or create deployment with: az spring app deployment create', str(context.exception)) \ No newline at end of file + self.assertEqual('No production deployment found, use --deployment to specify deployment or create deployment with: az spring app deployment create', str(context.exception)) diff --git a/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py b/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py index fce9c91bffe..7b582935c8e 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py @@ -150,10 +150,11 @@ def test_application_accelerator(self, resource_group, spring): self.check('properties.provisioningState', "Succeeded") ]) - self.cmd('spring application-accelerator create -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', "Succeeded") - ]) + self.cmd('spring application-accelerator create -g {rg} -s {serviceName}', + checks=[ + self.check('properties.provisioningState', "Succeeded") + ] + ) self.cmd('spring dev-tool show -g {rg} -s {serviceName}', checks=[ self.check('properties.features.applicationAccelerator.state', 'Enabled') diff --git a/src/spring/azext_spring/tests/latest/test_asa_create.py b/src/spring/azext_spring/tests/latest/test_asa_create.py index 7345fc1b811..7e5c27b8cab 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_create.py +++ b/src/spring/azext_spring/tests/latest/test_asa_create.py @@ -54,9 +54,9 @@ def setUp(self): def _get_sku(self, tier='Standard'): return models.Sku( - tier=tier, - name=_get_sku_name(tier) - ) + tier=tier, + name=_get_sku_name(tier) + ) @mock.patch('azext_spring._utils.cf_resource_groups', _cf_resource_group) def _execute(self, resource_group, name, **kwargs): diff --git a/src/spring/azext_spring/tests/latest/test_asa_gateway.py b/src/spring/azext_spring/tests/latest/test_asa_gateway.py index d1edc1da88a..8ed979b371f 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_gateway.py +++ b/src/spring/azext_spring/tests/latest/test_asa_gateway.py @@ -90,23 +90,29 @@ def test_gateway(self): ]) self.cmd('spring gateway route-config create -g {rg} -s {serviceName} -n {routeName} ' - '--app-name customers-service --routes-file {routeFile}', checks=[ - self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/customers-service'), - self.check('properties.provisioningState', "Succeeded") - ]) + '--app-name customers-service --routes-file {routeFile}', + checks=[ + self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/customers-service'), + self.check('properties.provisioningState', "Succeeded") + ] + ) self.cmd('spring gateway route-config update -g {rg} -s {serviceName} -n {routeName} ' - '--app-name vets-service --routes-file {routesFileV2}', checks=[ - self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/vets-service'), - self.check('properties.provisioningState', "Succeeded"), - self.check('properties.ssoEnabled', True) - ]) + '--app-name vets-service --routes-file {routesFileV2}', + checks=[ + self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/vets-service'), + self.check('properties.provisioningState', "Succeeded"), + self.check('properties.ssoEnabled', True) + ] + ) self.cmd('spring gateway route-config update -g {rg} -s {serviceName} -n {routeName} ' - '--app-name vets-service --routes-file {routesFileV2}', checks=[ - self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/vets-service'), - self.check('properties.provisioningState', "Succeeded") - ]) + '--app-name vets-service --routes-file {routesFileV2}', + checks=[ + self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/vets-service'), + self.check('properties.provisioningState', "Succeeded") + ] + ) result = self.cmd('spring gateway route-config list -g {rg} -s {serviceName}').get_output_in_json() self.assertTrue(len(result) > 0) diff --git a/src/spring/azext_spring/tests/latest/test_asa_gateway_response_cache.py b/src/spring/azext_spring/tests/latest/test_asa_gateway_response_cache.py index cda02aa0389..7441775027e 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_gateway_response_cache.py +++ b/src/spring/azext_spring/tests/latest/test_asa_gateway_response_cache.py @@ -71,9 +71,9 @@ def test_response_cache(self): self.cmd( 'spring gateway update -g {rg} -s {serviceName} --response-cache-ttl 11m --response-cache-scope Route', checks=[ - self.check('properties.responseCacheProperties.responseCacheType', 'LocalCachePerRoute'), - self.check('properties.responseCacheProperties.size', '10KB'), - self.check('properties.responseCacheProperties.timeToLive', '11m')]) + self.check('properties.responseCacheProperties.responseCacheType', 'LocalCachePerRoute'), + self.check('properties.responseCacheProperties.size', '10KB'), + self.check('properties.responseCacheProperties.timeToLive', '11m')]) # Update with nothing changed should be succeeded. self.cmd('spring gateway update -g {rg} -s {serviceName}', checks=[ @@ -89,9 +89,9 @@ def test_response_cache(self): self.cmd( 'spring gateway update -g {rg} -s {serviceName} --enable-response-cache --response-cache-ttl 11m --response-cache-scope Route', checks=[ - self.check('properties.responseCacheProperties.responseCacheType', 'LocalCachePerRoute'), - self.check('properties.responseCacheProperties.size', None), - self.check('properties.responseCacheProperties.timeToLive', '11m')]) + self.check('properties.responseCacheProperties.responseCacheType', 'LocalCachePerRoute'), + self.check('properties.responseCacheProperties.size', None), + self.check('properties.responseCacheProperties.timeToLive', '11m')]) self.cmd( 'spring gateway update -g {rg} -s {serviceName} --response-cache-size 13MB --response-cache-ttl default --response-cache-scope Instance', diff --git a/src/spring/azext_spring/tests/latest/test_asa_gateway_validator.py b/src/spring/azext_spring/tests/latest/test_asa_gateway_validator.py index 2958c8f6e02..f9100166e6a 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_gateway_validator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_gateway_validator.py @@ -80,9 +80,11 @@ def _test_valid_response_cache_size(self, ns): def test_response_cache_ttl(self): invalid_cache_ttl_list = ["-2", "0", ",", "00h", "0m", "-1s", "09m", "12345678901s"] - valid_cache_ttl_list = ["1234567890h", "1000h", "100h", "10h", "1h", - "1234567890m", "1000m", "100m", "10m", "1m", - "1234567890s", "1000s", "100s", "10s", "1s"] + valid_cache_ttl_list = [ + "1234567890h", "1000h", "100h", "10h", "1h", + "1234567890m", "1000m", "100m", "10m", "1m", + "1234567890s", "1000s", "100s", "10s", "1s" + ] for size in invalid_cache_ttl_list: ns = Namespace(response_cache_ttl=size) self._test_invalid_response_cache_ttl(ns) @@ -188,4 +190,3 @@ def test_validate_gateway_response_cache(self): for ns in valid_ns_list: _validate_gateway_response_cache(ns) - diff --git a/src/spring/azext_spring/tests/latest/test_asa_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_scenario.py index c3687596498..5335fae0946 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_scenario.py @@ -134,17 +134,19 @@ def test_load_public_cert_to_app(self, resource_group, spring, app): self.cmd( 'spring certificate show --name {digiCert} -g {rg} -s {serviceName}', checks=[ - self.check('name', '{digiCert}') - ]) + self.check('name', '{digiCert}') + ] + ) self.cmd( 'spring certificate show --name {baltiCert} -g {rg} -s {serviceName}', checks=[ - self.check('name', '{baltiCert}') - ]) + self.check('name', '{baltiCert}') + ] + ) cert_result = self.cmd( 'spring certificate list -g {rg} -s {serviceName}').get_output_in_json() - self.assertTrue(len(cert_result) >= 2) # in case there are other cert resources + self.assertTrue(len(cert_result) >= 2) # in case there are other cert resources self.cmd( 'spring app create --name {app} -f {loadCertPath} -g {rg} -s {serviceName}') @@ -193,4 +195,4 @@ def test_enable_planned_maintenance(self, resource_group, spring): self.cmd('spring update -g {resource_group} -n {serviceName} --enable-planned-maintenance --planned-maintenance-day Friday --planned-maintenance-start-hour 10', checks=[ self.check('properties.maintenanceScheduleConfiguration.day', 'Friday'), self.check('properties.maintenanceScheduleConfiguration.hour', 10) - ]) \ No newline at end of file + ]) diff --git a/src/spring/azext_spring/tests/latest/test_asa_service_registry.py b/src/spring/azext_spring/tests/latest/test_asa_service_registry.py index f02fa19c693..d729eef3e65 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_service_registry.py +++ b/src/spring/azext_spring/tests/latest/test_asa_service_registry.py @@ -17,7 +17,7 @@ class ServiceRegistryTest(ScenarioTest): @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) @SpringAppNamePreparer() def test_service_registry(self, resource_group, spring, app): - + self.kwargs.update({ 'serviceName': spring, 'rg': resource_group, @@ -25,14 +25,14 @@ def test_service_registry(self, resource_group, spring, app): }) self.cmd('spring app create -g {rg} -s {serviceName} -n {app}') - + self.cmd('spring service-registry show -g {rg} -s {serviceName}', checks=[ self.check('properties.provisioningState', "Succeeded") ]) self.cmd('spring service-registry bind --app {app} -g {rg} -s {serviceName}', checks=[ self.check('properties.addonConfigs.serviceRegistry.resourceId', - "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/serviceRegistries/default".format(self.get_subscription_id(), resource_group, spring)) + "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/serviceRegistries/default".format(self.get_subscription_id(), resource_group, spring)) ]) self.cmd('spring app show -n {app} -g {rg} -s {serviceName}') self.cmd('spring service-registry unbind --app {app} -g {rg} -s {serviceName}') diff --git a/src/spring/azext_spring/tests/latest/test_asa_update.py b/src/spring/azext_spring/tests/latest/test_asa_update.py index 5c08b3abf61..8800d1720c3 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_update.py +++ b/src/spring/azext_spring/tests/latest/test_asa_update.py @@ -18,6 +18,7 @@ logger = get_logger(__name__) free_mock_client = mock.MagicMock() + def _get_test_cmd(): cli_ctx = DummyCli() cli_ctx.data['subscription_id'] = '00000000-0000-0000-0000-000000000000' diff --git a/src/spring/azext_spring/tests/latest/test_asa_validator.py b/src/spring/azext_spring/tests/latest/test_asa_validator.py index 717e72c5f31..1936da6c96a 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_validator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_validator.py @@ -284,6 +284,7 @@ def _mock_get(offer_type, publisher_id, offer_id, plan_id): term = mock.MagicMock() term.accepted = accepted return term + def _mock_provider_get(namespace): provider = mock.MagicMock() provider.registration_state = 'Registered' if registered else 'NotRegistered' @@ -295,15 +296,19 @@ def _mock_provider_get(namespace): client.providers.get = _mock_provider_get return client + def _mock_happy_client(cli_ctx, client_type, **kwargs): return _mock_term_client(True, True) + def _mock_not_accepted_term_client(cli_ctx, client_type, **kwargs): return _mock_term_client(False, True) + def _mock_not_registered_client(cli_ctx, client_type, **kwargs): return _mock_term_client(True, False) + class TestSkuValidator(unittest.TestCase): @mock.patch('azure.cli.core.commands.client_factory.get_mgmt_service_client', _mock_happy_client) def test_happy_path(self): @@ -324,4 +329,3 @@ def test_provider_not_registered(self): with self.assertRaises(InvalidArgumentValueError) as context: validate_sku(_get_test_cmd(), ns) self.assertTrue('Microsoft.SaaS resource provider is not registered.' in str(context.exception)) - From 40299099c605e879be08ef7231690e1623b17141 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 17:42:00 +0800 Subject: [PATCH 12/19] Fix check style errors --- .../azext_spring/_validators_enterprise.py | 4 +- ...app_managed_identity_force_set_scenario.py | 6 +- .../test_app_managed_identity_scenario.py | 4 +- ..._create_app_with_both_identity_scenario.py | 2 +- ..._create_app_with_user_identity_scenario.py | 2 +- .../tests/latest/custom_preparers.py | 1 + .../latest/custom_recording_processor.py | 2 +- .../tests/latest/test_asa_accelerator.py | 101 +++++++++--------- .../tests/latest/test_asa_api_portal.py | 17 ++- .../latest/test_asa_api_portal_try_out_api.py | 2 + .../azext_spring/tests/latest/test_asa_apm.py | 3 - .../azext_spring/tests/latest/test_asa_app.py | 2 +- .../latest/test_asa_app_insights_scenario.py | 4 +- .../tests/latest/test_asa_app_scenario.py | 4 +- .../tests/latest/test_asa_app_validator.py | 1 - .../test_asa_application_accelerator.py | 30 +++--- ...t_asa_application_configuration_service.py | 11 +- .../latest/test_asa_application_live_view.py | 15 ++- .../test_asa_build_service_build_scenario.py | 2 +- ...test_asa_build_service_builder_scenario.py | 4 +- .../latest/test_asa_buildpack_binding.py | 36 ++++--- .../tests/latest/test_asa_certificate.py | 1 + .../tests/latest/test_asa_create.py | 14 +-- .../tests/latest/test_asa_gateway.py | 25 ++--- .../latest/test_asa_gateway_response_cache.py | 2 + .../latest/test_asa_gateway_validator.py | 18 +--- .../tests/latest/test_asa_scenario.py | 10 +- 27 files changed, 154 insertions(+), 169 deletions(-) diff --git a/src/spring/azext_spring/_validators_enterprise.py b/src/spring/azext_spring/_validators_enterprise.py index d622a873c70..14ac40e8833 100644 --- a/src/spring/azext_spring/_validators_enterprise.py +++ b/src/spring/azext_spring/_validators_enterprise.py @@ -452,7 +452,7 @@ def _validate_gateway_response_cache_scope(namespace): def _validate_gateway_response_cache_size(namespace): if namespace.response_cache_size is not None: size = namespace.response_cache_size - if type(size) != str: + if not isinstance(size, str): raise InvalidArgumentValueError('--response-cache-size should be a string') if GATEWAY_RESPONSE_CACHE_SIZE_RESET_VALUE.lower() == size.lower(): # Normalize the input @@ -467,7 +467,7 @@ def _validate_gateway_response_cache_size(namespace): def _validate_gateway_response_cache_ttl(namespace): if namespace.response_cache_ttl is not None: ttl = namespace.response_cache_ttl - if type(ttl) != str: + if not isinstance(ttl, str): raise InvalidArgumentValueError('--response-cache-ttl should be a string') if GATEWAY_RESPONSE_CACHE_TTL_RESET_VALUE.lower() == ttl.lower(): # Normalize the input diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_scenario.py index da5dcc20dc1..abaa776b9bf 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_scenario.py @@ -66,7 +66,7 @@ def test_app_identity_force_set(self): self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) - self.assertTrue(type(user_identity_dict) == dict) + self.assertTrue(isinstance(user_identity_dict, dict)) self.assertEquals(1, len(user_identity_dict)) self.assertTrue(self._contains_user_id_1(user_identity_dict.keys())) @@ -79,7 +79,7 @@ def test_app_identity_force_set(self): self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) - self.assertTrue(type(user_identity_dict) == dict) + self.assertTrue(isinstance(user_identity_dict, dict)) self.assertEquals(1, len(user_identity_dict)) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) @@ -92,7 +92,7 @@ def test_app_identity_force_set(self): self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) - self.assertTrue(type(user_identity_dict) == dict) + self.assertTrue(isinstance(user_identity_dict, dict)) self.assertEquals(2, len(user_identity_dict)) self.assertTrue(self._contains_user_id_1(user_identity_dict.keys())) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py index 4606c44be34..e3716394918 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py @@ -78,7 +78,7 @@ def test_app_identity_crud(self): self.assertTrue(len(user_identity_dict) == 1) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) - self.cmd('spring app identity remove -n {app} -g {rg} -s {serviceName} --user-assigned {ua2}',checks=[ + self.cmd('spring app identity remove -n {app} -g {rg} -s {serviceName} --user-assigned {ua2}', checks=[ self.check('identity.type', ManagedIdentityType.SYSTEM_ASSIGNED, case_sensitive=False), self.exists('identity.tenantId'), self.exists('identity.principalId'), @@ -95,7 +95,7 @@ def test_app_identity_crud(self): self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) - self.assertTrue(type(user_identity_dict) == dict) + self.assertTrue(isinstance(user_identity_dict, dict)) self.assertTrue(self._contains_user_id_1(user_identity_dict.keys())) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_both_identity_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_both_identity_scenario.py index f0bf8dd7fe4..59ddea22ba8 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_both_identity_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_both_identity_scenario.py @@ -49,7 +49,7 @@ def test_create_app_with_both_identity(self): self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) - self.assertTrue(type(user_identity_dict) == dict) + self.assertTrue(isinstance(user_identity_dict, dict)) self.assertEquals(len(user_identity_dict), 2) self.assertTrue(self._contains_user_id_1(user_identity_dict.keys())) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_user_identity_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_user_identity_scenario.py index 145ab812973..86fccbf81a2 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_user_identity_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_user_identity_scenario.py @@ -49,7 +49,7 @@ def test_create_app_with_user_identity(self): self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) - self.assertTrue(type(user_identity_dict) == dict) + self.assertTrue(isinstance(user_identity_dict, dict)) self.assertEquals(len(user_identity_dict), 2) self.assertTrue(self._contains_user_id_1(user_identity_dict.keys())) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) diff --git a/src/spring/azext_spring/tests/latest/custom_preparers.py b/src/spring/azext_spring/tests/latest/custom_preparers.py index a9f80a3b0fd..af7ce985032 100644 --- a/src/spring/azext_spring/tests/latest/custom_preparers.py +++ b/src/spring/azext_spring/tests/latest/custom_preparers.py @@ -53,6 +53,7 @@ def _safe_exec(self, cmd): except Exception: pass + class SpringSingleValueReplacer(RegexSingleValueReplacer): def __init__(self, dev_setting_name, moniker): super(SpringSingleValueReplacer, self).__init__(re.compile(f'(? 0) - self.cmd('spring application-accelerator predefined-accelerator show -n {name} -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', "Succeeded"), - self.check('properties.state', "Enabled") - ]) + self.cmd('spring application-accelerator predefined-accelerator show -n {name} -g {rg} -s {serviceName}', + checks=[ + self.check('properties.provisioningState', "Succeeded"), + self.check('properties.state', "Enabled") + ]) self.cmd('spring application-accelerator predefined-accelerator disable -n {name} -g {rg} -s {serviceName}') - self.cmd('spring application-accelerator predefined-accelerator show -n {name} -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', "Succeeded"), - self.check('properties.state', "Disabled") - ]) + self.cmd('spring application-accelerator predefined-accelerator show -n {name} -g {rg} -s {serviceName}', + checks=[ + self.check('properties.provisioningState', "Succeeded"), + self.check('properties.state', "Disabled") + ]) self.cmd('spring application-accelerator predefined-accelerator enable -n {name} -g {rg} -s {serviceName}') - self.cmd('spring application-accelerator predefined-accelerator show -n {name} -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', "Succeeded"), - self.check('properties.state', "Enabled") - ]) + self.cmd('spring application-accelerator predefined-accelerator show -n {name} -g {rg} -s {serviceName}', + checks=[ + self.check('properties.provisioningState', "Succeeded"), + self.check('properties.state', "Enabled") + ]) @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) @@ -64,23 +65,23 @@ def test_customized_accelerator(self, resource_group, spring): 'gitBranch': 'master', }) - self.cmd('spring application-accelerator customized-accelerator create -n {name} -g {rg} -s {serviceName} --display-name {displayName} --git-url {gitUrl} --git-branch {gitBranch} --git-interval 10', - checks=[ - self.check('properties.provisioningState', "Succeeded") - ]) + self.cmd('spring application-accelerator customized-accelerator create -n {name} -g {rg} -s {serviceName} --display-name {displayName} --git-url {gitUrl} --git-branch {gitBranch} --git-interval 10', + checks=[ + self.check('properties.provisioningState', "Succeeded") + ]) - self.cmd('spring application-accelerator customized-accelerator update -n {name} -g {rg} -s {serviceName} --display-name {displayName} --git-url {gitUrl} --git-branch {gitBranch} --description desc', - checks=[ - self.check('properties.provisioningState', "Succeeded") - ]) + self.cmd('spring application-accelerator customized-accelerator update -n {name} -g {rg} -s {serviceName} --display-name {displayName} --git-url {gitUrl} --git-branch {gitBranch} --description desc', + checks=[ + self.check('properties.provisioningState', "Succeeded") + ]) result = self.cmd('spring application-accelerator customized-accelerator list -g {rg} -s {serviceName}').get_output_in_json() self.assertTrue(len(result) == 1) - self.cmd('spring application-accelerator customized-accelerator show -n {name} -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', "Succeeded") - ]) + self.cmd('spring application-accelerator customized-accelerator show -n {name} -g {rg} -s {serviceName}', + checks=[ + self.check('properties.provisioningState', "Succeeded") + ]) self.cmd('spring application-accelerator customized-accelerator delete -n {name} -g {rg} -s {serviceName}') @@ -101,26 +102,26 @@ def test_customized_accelerator_of_fragment_type(self, resource_group, spring): 'gitBranch': 'main', }) - self.cmd('spring application-accelerator customized-accelerator create -n {name} -g {rg} -s {serviceName} --type Fragment --display-name {displayName} --git-sub-path {gitSubPath} --git-url {gitUrl} --git-branch {gitBranch} --git-interval 10', - checks=[ - self.check('properties.acceleratorType', "Fragment"), - self.check('properties.gitRepository.subPath', "java-version"), - self.check('properties.imports', ["java-version"]), - self.check('properties.provisioningState', "Succeeded") - ]) - - self.cmd('spring application-accelerator customized-accelerator update -n {name} -g {rg} -s {serviceName} --type Fragment --display-name {displayName} --git-sub-path {gitSubPath} --git-url {gitUrl} --git-branch {gitBranch} --description desc', - checks=[ - self.check('properties.acceleratorType', "Fragment"), - self.check('properties.gitRepository.subPath', "java-version"), - self.check('properties.imports', ["java-version"]), - self.check('properties.provisioningState', "Succeeded") - ]) - - self.cmd('spring application-accelerator customized-accelerator show -n {name} -g {rg} -s {serviceName}', - checks=[ - self.check('properties.acceleratorType', "Fragment"), - self.check('properties.gitRepository.subPath', "java-version"), - self.check('properties.imports', ["java-version"]), - self.check('properties.provisioningState', "Succeeded") - ]) + self.cmd('spring application-accelerator customized-accelerator create -n {name} -g {rg} -s {serviceName} --type Fragment --display-name {displayName} --git-sub-path {gitSubPath} --git-url {gitUrl} --git-branch {gitBranch} --git-interval 10', + checks=[ + self.check('properties.acceleratorType', "Fragment"), + self.check('properties.gitRepository.subPath', "java-version"), + self.check('properties.imports', ["java-version"]), + self.check('properties.provisioningState', "Succeeded") + ]) + + self.cmd('spring application-accelerator customized-accelerator update -n {name} -g {rg} -s {serviceName} --type Fragment --display-name {displayName} --git-sub-path {gitSubPath} --git-url {gitUrl} --git-branch {gitBranch} --description desc', + checks=[ + self.check('properties.acceleratorType', "Fragment"), + self.check('properties.gitRepository.subPath', "java-version"), + self.check('properties.imports', ["java-version"]), + self.check('properties.provisioningState', "Succeeded") + ]) + + self.cmd('spring application-accelerator customized-accelerator show -n {name} -g {rg} -s {serviceName}', + checks=[ + self.check('properties.acceleratorType', "Fragment"), + self.check('properties.gitRepository.subPath', "java-version"), + self.check('properties.imports', ["java-version"]), + self.check('properties.provisioningState', "Succeeded") + ]) diff --git a/src/spring/azext_spring/tests/latest/test_asa_api_portal.py b/src/spring/azext_spring/tests/latest/test_asa_api_portal.py index bc271155804..0406ef67c1f 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_api_portal.py +++ b/src/spring/azext_spring/tests/latest/test_asa_api_portal.py @@ -30,6 +30,7 @@ # pylint: disable=line-too-long # pylint: disable=too-many-lines + class ApiPortalWrapper(SpringSubResourceWrapper): def __init__(self, resource_group_parameter_name='resource_group', @@ -76,8 +77,7 @@ def test_api_portal(self, resource_group, spring, sp_name, sp_password): self.check('properties.ssoProperties.issuerUri', "https://login.microsoftonline.com/72f988bf-86f1-41af-91ab-2d7cd011db47/v2.0"), self.check('properties.ssoProperties.scope', ["openid", "profile", "email"]), self.check('properties.provisioningState', "Succeeded") - ] - ) + ]) self.cmd('spring api-portal show -g {rg} -s {serviceName}', checks=[ self.check('properties.public', True), @@ -127,13 +127,12 @@ def test_custom_domain(self): 'asa', 'my-domain.microsoft.com') args = client.api_portal_custom_domains.begin_create_or_update.call_args_list - self.assertEqual(1, len(args)) # one call - self.assertEqual(5, len(args[0][0])) # 5 parameters + self.assertEqual(1, len(args)) # one call + self.assertEqual(5, len(args[0][0])) # 5 parameters self.assertEqual(('rg', 'asa', 'default', 'my-domain.microsoft.com'), args[0][0][0:4]) resource = args[0][0][4] self.assertIsNone(resource.properties.thumbprint) - def test_custom_domain_with_cert(self): def _get_cert(*_, **__): resp = models.CertificateResource( @@ -151,8 +150,8 @@ def _get_cert(*_, **__): 'my-domain.microsoft.com', 'my-cert') args = client.api_portal_custom_domains.begin_create_or_update.call_args_list - self.assertEqual(1, len(args)) # one call - self.assertEqual(5, len(args[0][0])) # 5 parameters + self.assertEqual(1, len(args)) # one call + self.assertEqual(5, len(args[0][0])) # 5 parameters self.assertEqual(('rg', 'asa', 'default', 'my-domain.microsoft.com'), args[0][0][0:4]) resource = args[0][0][4] self.assertEqual('my-thumbprint', resource.properties.thumbprint) @@ -180,6 +179,6 @@ def test_custom_domain_unbind(self): 'asa', 'my-domain.microsoft.com') args = client.api_portal_custom_domains.begin_delete.call_args_list - self.assertEqual(1, len(args)) # one call - self.assertEqual(4, len(args[0][0])) # 5 parameters + self.assertEqual(1, len(args)) # one call + self.assertEqual(4, len(args[0][0])) # 5 parameters self.assertEqual(('rg', 'asa', 'default', 'my-domain.microsoft.com'), args[0][0]) diff --git a/src/spring/azext_spring/tests/latest/test_asa_api_portal_try_out_api.py b/src/spring/azext_spring/tests/latest/test_asa_api_portal_try_out_api.py index f22251a842c..ee1e730b50f 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_api_portal_try_out_api.py +++ b/src/spring/azext_spring/tests/latest/test_asa_api_portal_try_out_api.py @@ -13,6 +13,8 @@ """ Mark record_only to use the recording files as the mocked server to run the tests. """ + + @record_only() class ApiPortalTryOutApiTest(ScenarioTest): diff --git a/src/spring/azext_spring/tests/latest/test_asa_apm.py b/src/spring/azext_spring/tests/latest/test_asa_apm.py index 82c5a7a2910..dcfd290ff4f 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_apm.py +++ b/src/spring/azext_spring/tests/latest/test_asa_apm.py @@ -5,7 +5,6 @@ # pylint: disable=line-too-long # pylint: disable=too-many-lines -import os from azure.cli.testsdk import (ScenarioTest) from azure.cli.testsdk.reverse_dependency import ( @@ -46,8 +45,6 @@ class ApmTest(ScenarioTest): @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) @TearDown() def test_apm(self, resource_group, spring): - py_path = os.path.abspath(os.path.dirname(__file__)) - self.kwargs.update({ 'serviceName': spring, 'rg': resource_group, diff --git a/src/spring/azext_spring/tests/latest/test_asa_app.py b/src/spring/azext_spring/tests/latest/test_asa_app.py index a61b44092c1..dffcaf9cf3d 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app.py @@ -580,7 +580,7 @@ def test_app_update_custom_container_deployment(self): deployment = self._get_deployment() deployment.properties.source.type = 'Container' deployment.properties.source.custom_container.container_image = 'my-image' - self._execute('rg', 'asc', 'app', deployment=deployment, env={'key':'value'}) + self._execute('rg', 'asc', 'app', deployment=deployment, env={'key': 'value'}) resource = self.patch_deployment_resource self.assertIsNone(resource.properties.source) self.assertEqual({'key': 'value'}, resource.properties.deployment_settings.environment_variables) diff --git a/src/spring/azext_spring/tests/latest/test_asa_app_insights_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_app_insights_scenario.py index b7f4f9bed24..a9c2ef6a0a5 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app_insights_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app_insights_scenario.py @@ -14,10 +14,10 @@ TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) ''' -Since the scenarios covered here involves a lot of Azure Spring service creation. +Since the scenarios covered here involves a lot of Azure Spring service creation. It will take around 5~10 minutes to create one. And may take 1~2 hours to finish all. So as a trade-off, mark it as record_only. It will run against the requests and responses -in yaml files under recordings fold. If the yaml file is not here, it will call to backend +in yaml files under recordings fold. If the yaml file is not here, it will call to backend and generate the yaml file again. ''' diff --git a/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py index c4890ce0589..73dcfbb5156 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app_scenario.py @@ -17,6 +17,7 @@ TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + class AppDeploy(ScenarioTest): def __init__(self, method_name): super(AppDeploy, self).__init__( @@ -29,7 +30,7 @@ def __init__(self, method_name): @SpringAppNamePreparer() def test_deploy_app(self, resource_group, spring, app): py_path = os.path.abspath(os.path.dirname(__file__)) - file_path = os.path.join(py_path, 'files/test.jar').replace("\\","/") + file_path = os.path.join(py_path, 'files/test.jar').replace("\\", "/") self.kwargs.update({ 'app': app, 'serviceName': spring, @@ -218,6 +219,7 @@ def test_blue_green_deployment(self, resource_group, spring, app): self.check('properties.active', False) ]) + @record_only() class CustomImageTest(ScenarioTest): diff --git a/src/spring/azext_spring/tests/latest/test_asa_app_validator.py b/src/spring/azext_spring/tests/latest/test_asa_app_validator.py index 021fedd876f..72eb2eb466d 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app_validator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app_validator.py @@ -175,7 +175,6 @@ def test_deployment_provide(self, client_factory_mock): ns.deployment.id) self.assertFalse(ns.deployment.properties.active) - @mock.patch('azext_spring._app_validator.cf_spring', autospec=True) def test_deployment_provide_but_not_found(self, client_factory_mock): client = mock.MagicMock() diff --git a/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py b/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py index 7b582935c8e..7c0b5568f49 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py @@ -8,7 +8,7 @@ from .custom_preparers import (SpringPreparer, SpringResourceGroupPreparer) from .custom_dev_setting_constant import SpringTestEnvironmentEnum from ...vendored_sdks.appplatform.v2023_11_01_preview import models -from ...application_accelerator import (application_accelerator_create as create, +from ...application_accelerator import (application_accelerator_create as create, application_accelerator_delete as delete) try: import unittest.mock as mock @@ -48,17 +48,18 @@ def _mock_dev_tool_portal(enable_accelerator): resource.properties.features = models.DevToolPortalFeatureSettings( application_accelerator=models.DevToolPortalFeatureDetail( state=models.DevToolPortalFeatureState.ENABLED if enable_accelerator \ - else models.DevToolPortalFeatureState.DISABLED - ) - ) + else models.DevToolPortalFeatureState.DISABLED)) return resource + def _mock_enabled_get_dev_tool_portal(*_): return _mock_dev_tool_portal(enable_accelerator=True) + def _mock_disabled_get_dev_tool_portal(*_): return _mock_dev_tool_portal(enable_accelerator=False) + class ApplicationAccelerator(unittest.TestCase): def __init__(self, methodName: str = ...): super().__init__(methodName=methodName) @@ -87,14 +88,12 @@ def test_asa_acc_create_dev_tool_portal_disable_wait(self): self.assertIsNotNone(self.created_resource) self.assertIsNone(self.dev_tool_portal) - @mock.patch('azext_spring.application_accelerator.get_dev_tool_portal', _mock_enabled_get_dev_tool_portal) def test_asa_acc_create_skip_configure_dev_tool_portal_wait(self): self._execute(create, _get_test_cmd(), None, 'asa', 'rg', False) self.assertIsNotNone(self.created_resource) self.assertIsNone(self.dev_tool_portal) - @mock.patch('azext_spring.application_accelerator.get_dev_tool_portal', _mock_disabled_get_dev_tool_portal) def test_asa_acc_create_configure_dev_tool_portal_wait(self): self._execute(create, _get_test_cmd(), None, 'asa', 'rg', False) @@ -103,7 +102,6 @@ def test_asa_acc_create_configure_dev_tool_portal_wait(self): self.assertEqual(models.DevToolPortalFeatureState.ENABLED, self.dev_tool_portal.properties.features.application_accelerator.state) - @mock.patch('azext_spring.application_accelerator.get_dev_tool_portal', _mock_not_get_dev_tool_portal) def test_asa_acc_delete_dev_tool_portal_disable_wait(self): self._execute(delete, _get_test_cmd(), None, 'asa', 'rg', False) @@ -111,7 +109,6 @@ def test_asa_acc_delete_dev_tool_portal_disable_wait(self): self.assertIsNone(self.dev_tool_portal) self.assertTrue(self.deleted) - @mock.patch('azext_spring.application_accelerator.get_dev_tool_portal', _mock_disabled_get_dev_tool_portal) def test_asa_acc_delete_skip_configure_dev_tool_portal_wait(self): self._execute(delete, _get_test_cmd(), None, 'asa', 'rg', False) @@ -119,7 +116,6 @@ def test_asa_acc_delete_skip_configure_dev_tool_portal_wait(self): self.assertTrue(self.deleted) self.assertIsNone(self.dev_tool_portal) - @mock.patch('azext_spring.application_accelerator.get_dev_tool_portal', _mock_enabled_get_dev_tool_portal) def test_asa_acc_delete_configure_dev_tool_portal_wait(self): self._execute(delete, _get_test_cmd(), None, 'asa', 'rg', False) @@ -130,10 +126,11 @@ def test_asa_acc_delete_configure_dev_tool_portal_wait(self): self.dev_tool_portal.properties.features.application_accelerator.state) ''' -Since the scenarios covered here depend on a Azure Spring service instance creation. -It cannot support live run. So mark it as record_only. +Since the scenarios covered here depend on a Azure Spring service instance creation. +It cannot support live run. So mark it as record_only. ''' + class ApiApplicationAcceleratorTest(ScenarioTest): @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE['resource_group_name']) @@ -153,17 +150,16 @@ def test_application_accelerator(self, resource_group, spring): self.cmd('spring application-accelerator create -g {rg} -s {serviceName}', checks=[ self.check('properties.provisioningState', "Succeeded") - ] - ) + ]) self.cmd('spring dev-tool show -g {rg} -s {serviceName}', checks=[ self.check('properties.features.applicationAccelerator.state', 'Enabled') ]) - self.cmd('spring application-accelerator show -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', "Succeeded") - ]) + self.cmd('spring application-accelerator show -g {rg} -s {serviceName}', + checks=[ + self.check('properties.provisioningState', "Succeeded") + ]) self.cmd('spring application-accelerator delete --yes -g {rg} -s {serviceName}') diff --git a/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py b/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py index 6ed4323dc0c..5fb00b96329 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py +++ b/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py @@ -13,6 +13,7 @@ # pylint: disable=line-too-long # pylint: disable=too-many-lines + class TearDown(SpringSubResourceWrapper): def __init__(self, resource_group_parameter_name='resource_group', @@ -59,15 +60,13 @@ def test_application_configuration_service(self, resource_group, spring, app): '-n {repo} --label {label} --patterns {patterns} --uri {uri}', checks=[ self.check('properties.provisioningState', "Succeeded") - ] - ) + ]) self.cmd('spring application-configuration-service git repo update -g {rg} -s {serviceName} ' '-n {repo} --label {label}', checks=[ self.check('properties.provisioningState', "Succeeded") - ] - ) + ]) result = self.cmd('spring application-configuration-service git repo list -g {rg} -s {serviceName}').get_output_in_json() self.assertTrue(len(result) > 0) @@ -78,7 +77,7 @@ def test_application_configuration_service(self, resource_group, spring, app): self.cmd('spring application-configuration-service bind --app {app} -g {rg} -s {serviceName}', checks=[ self.check('properties.addonConfigs.applicationConfigurationService.resourceId', - "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/configurationServices/default".format(self.get_subscription_id(), resource_group, spring)) + "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/configurationServices/default".format(self.get_subscription_id(), resource_group, spring)) ]) self.cmd('spring app show -n {app} -g {rg} -s {serviceName}') @@ -89,4 +88,4 @@ def test_application_configuration_service(self, resource_group, spring, app): self.check('properties.provisioningState', "Succeeded") ]) - self.cmd('spring application-configuration-service update -g {rg} -s {serviceName} --generation Gen2', checks=[self.check('properties.provisioningState', "Succeeded") ]) + self.cmd('spring application-configuration-service update -g {rg} -s {serviceName} --generation Gen2', checks=[self.check('properties.provisioningState', "Succeeded")]) diff --git a/src/spring/azext_spring/tests/latest/test_asa_application_live_view.py b/src/spring/azext_spring/tests/latest/test_asa_application_live_view.py index d3cfd1bee23..9a954879210 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_application_live_view.py +++ b/src/spring/azext_spring/tests/latest/test_asa_application_live_view.py @@ -23,6 +23,7 @@ logger = get_logger(__name__) free_mock_client = mock.MagicMock() + def _get_test_cmd(): cli_ctx = DummyCli() cli_ctx.data['subscription_id'] = '00000000-0000-0000-0000-000000000000' @@ -46,22 +47,22 @@ def _mock_dev_tool_portal(enable_live_view): resource.properties.features = models.DevToolPortalFeatureSettings( application_live_view=models.DevToolPortalFeatureDetail( state=models.DevToolPortalFeatureState.ENABLED if enable_live_view \ - else models.DevToolPortalFeatureState.DISABLED - ) - ) + else models.DevToolPortalFeatureState.DISABLED)) return resource def _mock_enabled_get_dev_tool_portal(*_): return _mock_dev_tool_portal(enable_live_view=True) + def _mock_disabled_get_dev_tool_portal(*_): return _mock_dev_tool_portal(enable_live_view=False) + class ApplicationLiveView(unittest.TestCase): def __init__(self, methodName: str = ...): super().__init__(methodName=methodName) self.created_resource = None - self.dev_tool_portal =None + self.dev_tool_portal = None self.deleted = False self.created_alv_request = None self.dev_tool_portal_request = None @@ -90,14 +91,12 @@ def test_asa_alv_create_dev_tool_portal_disable_wait(self): self.assertEqual('default', self.created_alv_request[0][0][2]) self.assertIsNone(self.dev_tool_portal) - @mock.patch('azext_spring.application_live_view.get_dev_tool_portal', _mock_enabled_get_dev_tool_portal) def test_asa_alv_create_skip_configure_dev_tool_portal_wait(self): self._execute(create, _get_test_cmd(), None, 'asa', 'rg', False) self.assertIsNotNone(self.created_resource) self.assertIsNone(self.dev_tool_portal) - @mock.patch('azext_spring.application_live_view.get_dev_tool_portal', _mock_disabled_get_dev_tool_portal) def test_asa_alv_create_configure_dev_tool_portal_wait(self): self._execute(create, _get_test_cmd(), None, 'asa', 'rg', False) @@ -109,7 +108,6 @@ def test_asa_alv_create_configure_dev_tool_portal_wait(self): self.assertEqual('asa', self.dev_tool_portal_request[0][0][1]) self.assertEqual('default', self.dev_tool_portal_request[0][0][2]) - @mock.patch('azext_spring.application_live_view.get_dev_tool_portal', _mock_not_get_dev_tool_portal) def test_asa_alv_delete_dev_tool_portal_disable_wait(self): self._execute(delete, _get_test_cmd(), None, 'asa', 'rg', False) @@ -117,7 +115,6 @@ def test_asa_alv_delete_dev_tool_portal_disable_wait(self): self.assertIsNone(self.dev_tool_portal) self.assertTrue(self.deleted) - @mock.patch('azext_spring.application_live_view.get_dev_tool_portal', _mock_disabled_get_dev_tool_portal) def test_asa_alv_delete_skip_configure_dev_tool_portal_wait(self): self._execute(delete, _get_test_cmd(), None, 'asa', 'rg', False) @@ -125,7 +122,6 @@ def test_asa_alv_delete_skip_configure_dev_tool_portal_wait(self): self.assertTrue(self.deleted) self.assertIsNone(self.dev_tool_portal) - @mock.patch('azext_spring.application_live_view.get_dev_tool_portal', _mock_enabled_get_dev_tool_portal) def test_asa_alv_delete_configure_dev_tool_portal_wait(self): self._execute(delete, _get_test_cmd(), None, 'asa', 'rg', False) @@ -135,6 +131,7 @@ def test_asa_alv_delete_configure_dev_tool_portal_wait(self): self.assertEqual(models.DevToolPortalFeatureState.DISABLED, self.dev_tool_portal.properties.features.application_live_view.state) + class LiveViewTest(ScenarioTest): @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE['resource_group_name']) diff --git a/src/spring/azext_spring/tests/latest/test_asa_build_service_build_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_build_service_build_scenario.py index beb89b02187..c6c64b85749 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_build_service_build_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_build_service_build_scenario.py @@ -11,6 +11,7 @@ # pylint: disable=line-too-long # pylint: disable=too-many-lines + @record_only() class BuildServiceBuildTest(ScenarioTest): def test_build(self): @@ -33,7 +34,6 @@ def test_build(self): ]) self.cmd('spring build-service build delete -n {name} -g {rg} --service {serviceName} -y') - def test_container_registry(self): self.kwargs.update({ 'serviceName': 'cli-unittest-e', diff --git a/src/spring/azext_spring/tests/latest/test_asa_build_service_builder_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_build_service_builder_scenario.py index 29f4ce9ef80..1a981163074 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_build_service_builder_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_build_service_builder_scenario.py @@ -15,7 +15,7 @@ # pylint: disable=line-too-long # pylint: disable=too-many-lines -BUILDER_NAME='test-builder' +BUILDER_NAME = 'test-builder' class TearDown(SpringSubResourceWrapper): @@ -41,7 +41,7 @@ class BuildServiceBuilderTest(ScenarioTest): @TearDown() def test_Builder(self, resource_group, spring): py_path = os.path.abspath(os.path.dirname(__file__)) - builder_file = os.path.join(py_path, 'files/build_service_builder.json').replace("\\","/") + builder_file = os.path.join(py_path, 'files/build_service_builder.json').replace("\\", "/") self.kwargs.update({ 'serviceName': spring, diff --git a/src/spring/azext_spring/tests/latest/test_asa_buildpack_binding.py b/src/spring/azext_spring/tests/latest/test_asa_buildpack_binding.py index 3d835d1165f..91a265c0155 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_buildpack_binding.py +++ b/src/spring/azext_spring/tests/latest/test_asa_buildpack_binding.py @@ -14,7 +14,8 @@ # pylint: disable=line-too-long # pylint: disable=too-many-lines -BINDING_NAME="binding" +BINDING_NAME = "binding" + class TearDown(SpringSubResourceWrapper): def __init__(self, @@ -33,6 +34,7 @@ def remove_resource(self, *_, **__): self._safe_exec('spring build-service builder buildpack-binding delete --name {} -g {} -s {} --yes'.format(BINDING_NAME, self.resource_group, self.spring)) self._safe_exec('spring build-service builder buildpack-binding delete --name {}-0 -g {} -s {} --yes'.format(BINDING_NAME, self.resource_group, self.spring)) + class BuildpackBindingTest(ScenarioTest): @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['resource_group_name']) @@ -53,27 +55,27 @@ def test_buildpack_binding(self, resource_group, spring): self.cmd('spring build-service builder buildpack-binding create --name {bindingName} --type {bindingType} \ --properties {properties} --secrets {secrets} -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', 'Succeeded'), - self.check('properties.bindingType', 'ApplicationInsights'), - self.check('properties.launchProperties.properties', {'a': 'b', 'b': 'c'}), - self.check('properties.launchProperties.secrets', {'x': '*', 'y': '*'}), - ]) + checks=[ + self.check('properties.provisioningState', 'Succeeded'), + self.check('properties.bindingType', 'ApplicationInsights'), + self.check('properties.launchProperties.properties', {'a': 'b', 'b': 'c'}), + self.check('properties.launchProperties.secrets', {'x': '*', 'y': '*'}), + ]) self.cmd('spring build-service builder buildpack-binding show --name {bindingName} -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', 'Succeeded'), - self.check('properties.bindingType', 'ApplicationInsights'), - ]) + checks=[ + self.check('properties.provisioningState', 'Succeeded'), + self.check('properties.bindingType', 'ApplicationInsights'), + ]) self.cmd('spring build-service builder buildpack-binding create --name {bindingName}-0 --type NewRelic \ --properties {properties} --secrets {secrets} -g {rg} -s {serviceName}', - checks=[ - self.check('properties.provisioningState', 'Succeeded'), - self.check('properties.bindingType', 'NewRelic'), - self.check('properties.launchProperties.properties', {'a': 'b', 'b': 'c'}), - self.check('properties.launchProperties.secrets', {'x': '*', 'y': '*'}), - ]) + checks=[ + self.check('properties.provisioningState', 'Succeeded'), + self.check('properties.bindingType', 'NewRelic'), + self.check('properties.launchProperties.properties', {'a': 'b', 'b': 'c'}), + self.check('properties.launchProperties.secrets', {'x': '*', 'y': '*'}), + ]) results = self.cmd('spring build-service builder buildpack-binding list -g {rg} -s {serviceName}').get_output_in_json() self.assertEqual(2, len(results)) diff --git a/src/spring/azext_spring/tests/latest/test_asa_certificate.py b/src/spring/azext_spring/tests/latest/test_asa_certificate.py index dba7857efe9..43b8fabd99a 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_certificate.py +++ b/src/spring/azext_spring/tests/latest/test_asa_certificate.py @@ -21,6 +21,7 @@ logger = get_logger(__name__) TEST_DIR = os.path.abspath(os.path.join(os.path.abspath(__file__), '..')) + def _get_test_cmd(): cli_ctx = DummyCli() cli_ctx.data['subscription_id'] = '00000000-0000-0000-0000-000000000000' diff --git a/src/spring/azext_spring/tests/latest/test_asa_create.py b/src/spring/azext_spring/tests/latest/test_asa_create.py index 7e5c27b8cab..f8ba2f333d0 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_create.py +++ b/src/spring/azext_spring/tests/latest/test_asa_create.py @@ -20,6 +20,7 @@ logger = get_logger(__name__) free_mock_client = mock.MagicMock() + def _get_test_cmd(): cli_ctx = DummyCli() cli_ctx.data['subscription_id'] = '00000000-0000-0000-0000-000000000000' @@ -46,12 +47,12 @@ class BasicTest(unittest.TestCase): def __init__(self, methodName: str = ...): super().__init__(methodName=methodName) self.created_resource = None - + def setUp(self): resp = super().setUp() free_mock_client.reset_mock() return resp - + def _get_sku(self, tier='Standard'): return models.Sku( tier=tier, @@ -122,7 +123,7 @@ def test_asa_enterprise_without_alv(self): self._execute('rg', 'asc', sku=self._get_sku('Enterprise'), enable_application_live_view=False, disable_app_insights=True) self.assertIsNone(self.alv_resource) self.assertIsNone(self.dev_tool) - + def test_asa_standard_with_alv(self): self._execute('rg', 'asc', sku=self._get_sku('Standard'), enable_application_live_view=True, disable_app_insights=True) self.assertIsNone(self.alv_resource) @@ -157,7 +158,7 @@ def test_asa_enterprise_without_acc(self): self._execute('rg', 'asc', sku=self._get_sku('Enterprise'), enable_application_accelerator=False, disable_app_insights=True) self.assertIsNone(self.acc_resource) self.assertIsNone(self.dev_tool) - + def test_asa_standard_with_acc(self): self._execute('rg', 'asc', sku=self._get_sku('Standard'), enable_application_accelerator=True, disable_app_insights=True) self.assertIsNone(self.acc_resource) @@ -182,7 +183,7 @@ def _get_ai_client(ctx, type): def __init__(self, methodName: str = ...): super().__init__(methodName=methodName) self.monitoring_settings_resource = None - + @mock.patch('azext_spring.custom.get_mgmt_service_client', _get_ai_client) def _execute(self, resource_group, name, **kwargs): client = kwargs.pop('client', None) or _get_basic_mock_client() @@ -307,6 +308,7 @@ def test_asa_create_enterprise_with_ingress_config(self): resource = self.created_resource self.assertEqual(100, resource.properties.network_profile.ingress_config.read_timeout_in_seconds) + class TestSpringAppCreateWithLogStreamConfig(BasicTest): def test_asa_create_standard_with_log_stream_config(self): self._execute('rg', 'asc', sku=self._get_sku('Standard'), enable_dataplane_public_endpoint=True, disable_app_insights=True) @@ -316,4 +318,4 @@ def test_asa_create_standard_with_log_stream_config(self): def test_asa_create_enterprise_with_log_stream_config(self): self._execute('rg', 'asc', sku=self._get_sku('Enterprise'), enable_dataplane_public_endpoint=True, disable_app_insights=True) resource = self.created_resource - self.assertEqual(True, resource.properties.vnet_addons.data_plane_public_endpoint) \ No newline at end of file + self.assertEqual(True, resource.properties.vnet_addons.data_plane_public_endpoint) diff --git a/src/spring/azext_spring/tests/latest/test_asa_gateway.py b/src/spring/azext_spring/tests/latest/test_asa_gateway.py index 8ed979b371f..3ba297a4629 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_gateway.py +++ b/src/spring/azext_spring/tests/latest/test_asa_gateway.py @@ -15,10 +15,10 @@ class GatewayTest(ScenarioTest): def test_gateway(self): py_path = os.path.abspath(os.path.dirname(__file__)) - routes_file = os.path.join(py_path, 'files/gateway_routes.json').replace("\\","/") - routes_file_v2 = os.path.join(py_path, 'files/gateway_routes_v2.json').replace("\\","/") - addon_configs_file = os.path.join(py_path, 'files/gateway_addon_configs.json').replace("\\","/") - + routes_file = os.path.join(py_path, 'files/gateway_routes.json').replace("\\", "/") + routes_file_v2 = os.path.join(py_path, 'files/gateway_routes_v2.json').replace("\\", "/") + addon_configs_file = os.path.join(py_path, 'files/gateway_addon_configs.json').replace("\\", "/") + self.kwargs.update({ 'serviceName': 'tx-enterprise', 'rg': 'tx', @@ -69,18 +69,16 @@ def test_gateway(self): self.check('properties.apmTypes', ["NewRelic", "ElasticAPM"]), self.check('properties.environmentVariables.properties', {'a': 'b', 'c': 'd'}), self.check('properties.environmentVariables.secrets', None), - self.check('properties.addonConfigs', {'javaOpts':'-Djava.awt.headless=true','sso':{'rolesAttributeName':'role','inactiveSessionExpirationInMinutes':1},'envs':[{'name':'xxx','value':'yyy'},{'name':'xxx1','value':'yyy'}]}), + self.check('properties.addonConfigs', {'javaOpts': '-Djava.awt.headless=true', 'sso': {'rolesAttributeName': 'role', 'inactiveSessionExpirationInMinutes': 1}, 'envs': [{'name': 'xxx', 'value': 'yyy'}, {'name': 'xxx1', 'value': 'yyy'}]}), self.check('properties.provisioningState', "Succeeded") - ] - ) + ]) self.cmd('spring gateway update -g {rg} -s {serviceName} ' '--apm-types '' --apms test-ai', checks=[ self.check('properties.apms', [{'resourceId': '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apms/test-ai'}]), self.check('properties.provisioningState', "Succeeded") - ] - ) + ]) self.cmd('spring gateway show -g {rg} -s {serviceName}', checks=[ self.check('properties.public', True), @@ -94,8 +92,7 @@ def test_gateway(self): checks=[ self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/customers-service'), self.check('properties.provisioningState', "Succeeded") - ] - ) + ]) self.cmd('spring gateway route-config update -g {rg} -s {serviceName} -n {routeName} ' '--app-name vets-service --routes-file {routesFileV2}', @@ -103,16 +100,14 @@ def test_gateway(self): self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/vets-service'), self.check('properties.provisioningState', "Succeeded"), self.check('properties.ssoEnabled', True) - ] - ) + ]) self.cmd('spring gateway route-config update -g {rg} -s {serviceName} -n {routeName} ' '--app-name vets-service --routes-file {routesFileV2}', checks=[ self.check('properties.appResourceId', '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/tx/providers/Microsoft.AppPlatform/Spring/tx-enterprise/apps/vets-service'), self.check('properties.provisioningState', "Succeeded") - ] - ) + ]) result = self.cmd('spring gateway route-config list -g {rg} -s {serviceName}').get_output_in_json() self.assertTrue(len(result) > 0) diff --git a/src/spring/azext_spring/tests/latest/test_asa_gateway_response_cache.py b/src/spring/azext_spring/tests/latest/test_asa_gateway_response_cache.py index 7441775027e..e750bdaf762 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_gateway_response_cache.py +++ b/src/spring/azext_spring/tests/latest/test_asa_gateway_response_cache.py @@ -13,6 +13,8 @@ """ Mark record_only to use the recording files as the mocked server to run the tests. """ + + @record_only() class GatewayResponseCacheTest(ScenarioTest): def test_response_cache(self): diff --git a/src/spring/azext_spring/tests/latest/test_asa_gateway_validator.py b/src/spring/azext_spring/tests/latest/test_asa_gateway_validator.py index f9100166e6a..b973b6ea440 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_gateway_validator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_gateway_validator.py @@ -9,8 +9,8 @@ from ..._gateway_constant import (GATEWAY_RESPONSE_CACHE_SCOPE_ROUTE, GATEWAY_RESPONSE_CACHE_SCOPE_INSTANCE, GATEWAY_RESPONSE_CACHE_SIZE_RESET_VALUE, GATEWAY_RESPONSE_CACHE_TTL_RESET_VALUE) from ..._validators_enterprise import (_validate_gateway_response_cache, _validate_gateway_response_cache_exclusive, - _validate_gateway_response_cache_scope, _validate_gateway_response_cache_size, - _validate_gateway_response_cache_ttl) + _validate_gateway_response_cache_scope, _validate_gateway_response_cache_size, + _validate_gateway_response_cache_ttl) class TestGatewayValidator(unittest.TestCase): @@ -28,18 +28,15 @@ def test_response_cache_scope(self): ns = Namespace(response_cache_scope=valid_scope) self._test_valid_response_cache_scope(ns, GATEWAY_RESPONSE_CACHE_SCOPE_INSTANCE) - def _test_invalid_response_cache_scope(self, ns): with self.assertRaises(InvalidArgumentValueError) as context: _validate_gateway_response_cache_scope(ns) self.assertEqual("The allowed values for '--response-cache-scope' are [Route, Instance]", str(context.exception)) - def _test_valid_response_cache_scope(self, ns, expectedScope): _validate_gateway_response_cache_scope(ns) self.assertEqual(expectedScope, ns.response_cache_scope) - def test_response_cache_size(self): invalid_cache_size_list = ["-2", "0", ",", "00GB", "0MB", "-1MB", "09KB", "12345678901GB"] valid_cache_size_list = ["1234567890GB", "1000GB", "100GB", "10GB", "1GB", @@ -65,7 +62,6 @@ def test_response_cache_size(self): _validate_gateway_response_cache_size(ns) self.assertTrue(ns.response_cache_size == GATEWAY_RESPONSE_CACHE_SIZE_RESET_VALUE) - def _test_invalid_response_cache_size(self, ns): with self.assertRaises(InvalidArgumentValueError) as context: _validate_gateway_response_cache_size(ns) @@ -73,11 +69,9 @@ def _test_invalid_response_cache_size(self, ns): ns.response_cache_size, r"^[1-9][0-9]{0,9}(GB|MB|KB)$" ), str(context.exception)) - def _test_valid_response_cache_size(self, ns): _validate_gateway_response_cache_size(ns) - def test_response_cache_ttl(self): invalid_cache_ttl_list = ["-2", "0", ",", "00h", "0m", "-1s", "09m", "12345678901s"] valid_cache_ttl_list = [ @@ -105,7 +99,6 @@ def test_response_cache_ttl(self): _validate_gateway_response_cache_ttl(ns) self.assertTrue(ns.response_cache_ttl == GATEWAY_RESPONSE_CACHE_TTL_RESET_VALUE) - def _test_invalid_response_cache_ttl(self, ns): with self.assertRaises(InvalidArgumentValueError) as context: _validate_gateway_response_cache_ttl(ns) @@ -113,11 +106,9 @@ def _test_invalid_response_cache_ttl(self, ns): ns.response_cache_ttl, r"^[1-9][0-9]{0,9}(h|m|s)$" ), str(context.exception)) - def _test_valid_response_cache_ttl(self, ns): _validate_gateway_response_cache_ttl(ns) - def test_validate_gateway_response_cache_exclusive(self): invalid_ns_list = [ Namespace(enable_response_cache=False, response_cache_scope="Route", response_cache_size="10GB", @@ -146,12 +137,11 @@ def test_validate_gateway_response_cache_exclusive(self): with self.assertRaises(InvalidArgumentValueError) as context: _validate_gateway_response_cache_exclusive(ns) self.assertEqual("Conflict detected: Parameters in ['--response-cache-scope', " - "'--response-cache-scope', '--response-cache-ttl'] " - "cannot be set together with '--enable-response-cache false'.", str(context.exception)) + "'--response-cache-scope', '--response-cache-ttl'] " + "cannot be set together with '--enable-response-cache false'.", str(context.exception)) for ns in valid_ns_list: _validate_gateway_response_cache_exclusive(ns) - def test_validate_gateway_response_cache(self): valid_ns_list = [ Namespace(response_cache_scope="Route", response_cache_size="10GB", response_cache_ttl="10s", diff --git a/src/spring/azext_spring/tests/latest/test_asa_scenario.py b/src/spring/azext_spring/tests/latest/test_asa_scenario.py index 5335fae0946..9a447384fa8 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_scenario.py +++ b/src/spring/azext_spring/tests/latest/test_asa_scenario.py @@ -90,7 +90,7 @@ def __init__(self, def create_resource(self, *_, **kwargs): self.resource_group = self._get_resource_group(**kwargs) self.spring = self._get_spring(**kwargs) - + def remove_resource(self, *_, **__): self.live_only_execute(self.cli_ctx, 'spring certificate remove -g {} -s {} -n balti-cert'.format(self.resource_group, self.spring)) self.live_only_execute(self.cli_ctx, 'spring certificate remove -g {} -s {} -n digi-cert'.format(self.resource_group, self.spring)) @@ -105,9 +105,9 @@ class SslTests(ScenarioTest): @CertTearDown() def test_load_public_cert_to_app(self, resource_group, spring, app): py_path = os.path.abspath(os.path.dirname(__file__)) - baltiCertPath = os.path.join(py_path, 'files/BaltimoreCyberTrustRoot.crt.pem').replace("\\","/") - digiCertPath = os.path.join(py_path, 'files/DigiCertGlobalRootCA.crt.pem').replace("\\","/") - loadCertPath = os.path.join(py_path, 'files/load_certificate.json').replace("\\","/") + baltiCertPath = os.path.join(py_path, 'files/BaltimoreCyberTrustRoot.crt.pem').replace("\\", "/") + digiCertPath = os.path.join(py_path, 'files/DigiCertGlobalRootCA.crt.pem').replace("\\", "/") + loadCertPath = os.path.join(py_path, 'files/load_certificate.json').replace("\\", "/") self.kwargs.update({ 'baltiCert': 'balti-cert', @@ -146,7 +146,7 @@ def test_load_public_cert_to_app(self, resource_group, spring, app): cert_result = self.cmd( 'spring certificate list -g {rg} -s {serviceName}').get_output_in_json() - self.assertTrue(len(cert_result) >= 2) # in case there are other cert resources + self.assertTrue(len(cert_result) >= 2) # in case there are other cert resources self.cmd( 'spring app create --name {app} -f {loadCertPath} -g {rg} -s {serviceName}') From d3e3c570c3a4b2b51e3f93f32d94529053025655 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Fri, 15 Dec 2023 18:04:19 +0800 Subject: [PATCH 13/19] Fix check style errors --- ...est_app_managed_identity_force_set_scenario.py | 3 --- ...st_app_managed_identity_force_set_validator.py | 12 ------------ .../test_app_managed_identity_remove.py | 15 --------------- .../test_app_managed_identity_scenario.py | 7 ++----- .../test_app_managed_identity_validator.py | 12 ------------ ...test_create_app_with_both_identity_scenario.py | 3 --- ..._create_app_with_managed_identity_validator.py | 13 ------------- ...st_create_app_with_system_identity_scenario.py | 1 - ...test_create_app_with_user_identity_scenario.py | 3 --- .../azext_spring/tests/latest/custom_preparers.py | 2 +- .../tests/latest/test_asa_accelerator.py | 7 ++----- .../tests/latest/test_asa_api_portal.py | 5 ++--- .../azext_spring/tests/latest/test_asa_app.py | 2 +- .../latest/test_asa_application_accelerator.py | 12 ++++++------ .../test_asa_application_configuration_service.py | 7 +++---- .../latest/test_asa_application_live_view.py | 9 +++++---- .../tests/latest/test_asa_buildpack_binding.py | 3 --- .../azext_spring/tests/latest/test_asa_create.py | 12 ++++++------ 18 files changed, 28 insertions(+), 100 deletions(-) diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_scenario.py index abaa776b9bf..1dfb2132eab 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_scenario.py @@ -112,15 +112,12 @@ def test_app_identity_force_set(self): self.check('identity', None) ]) - def _contains_user_id_1(self, keys): return MASKED_USER_IDENTITY_RESOURCE_ID_1.lower() in keys or USER_IDENTITY_RESOURCE_ID_1.lower() in keys - def _contains_user_id_2(self, keys): return MASKED_USER_IDENTITY_RESOURCE_ID_2.lower() in keys or USER_IDENTITY_RESOURCE_ID_2.lower() in keys - def _to_lower(self, str_dict): new_dict = {} for key in str_dict.keys(): diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_validator.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_validator.py index ba3c6936b84..7ebbe0c07b2 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_validator.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_force_set_validator.py @@ -23,37 +23,31 @@ def test_force_set_system_identity_valid_input_1(self): validate_app_force_set_system_identity_or_warning(ns) self.assertTrue("disable", ns.system_assigned) - def test_force_set_system_identity_valid_input_2(self): ns = Namespace(system_assigned="disable") validate_app_force_set_system_identity_or_warning(ns) self.assertTrue("disable", ns.system_assigned) - def test_force_set_system_identity_valid_input_3(self): ns = Namespace(system_assigned="DISABLE") validate_app_force_set_system_identity_or_warning(ns) self.assertTrue("disable", ns.system_assigned) - def test_force_set_system_identity_valid_input_4(self): ns = Namespace(system_assigned="enAble") validate_app_force_set_system_identity_or_warning(ns) self.assertTrue("enable", ns.system_assigned) - def test_force_set_system_identity_valid_input_5(self): ns = Namespace(system_assigned="enable") validate_app_force_set_system_identity_or_warning(ns) self.assertTrue("enable", ns.system_assigned) - def test_force_set_system_identity_valid_input_6(self): ns = Namespace(system_assigned="ENABLE") validate_app_force_set_system_identity_or_warning(ns) self.assertTrue("enable", ns.system_assigned) - def test_force_set_system_identity_invalid_input(self): ns = Namespace(system_assigned="randomestring") with self.assertRaises(InvalidArgumentValueError) as context: @@ -68,39 +62,33 @@ def test_valid_input_1(self): validate_app_force_set_user_identity_or_warning(ns) self.assertEquals("disable", ns.user_assigned[0]) - def test_valid_input_2(self): ns = Namespace(user_assigned=["disable"]) validate_app_force_set_user_identity_or_warning(ns) self.assertEquals("disable", ns.user_assigned[0]) - def test_valid_input_3(self): ns = Namespace(user_assigned=["DISABLE"]) validate_app_force_set_user_identity_or_warning(ns) self.assertEquals("disable", ns.user_assigned[0]) - def test_valid_input_4(self): ns = Namespace(user_assigned=[FAKE_UPPER_USER_IDENTITY_RESOURCE_ID_0]) validate_app_force_set_user_identity_or_warning(ns) self.assertEquals(FAKE_LOWER_USER_IDENTITY_RESOURCE_ID_0, ns.user_assigned[0]) - def test_valid_input_5(self): ns = Namespace(user_assigned=[FAKE_UPPER_USER_IDENTITY_RESOURCE_ID_0, FAKE_LOWER_USER_IDENTITY_RESOURCE_ID_1]) validate_app_force_set_user_identity_or_warning(ns) self.assertEquals(FAKE_LOWER_USER_IDENTITY_RESOURCE_ID_0, ns.user_assigned[0]) self.assertEquals(FAKE_LOWER_USER_IDENTITY_RESOURCE_ID_1, ns.user_assigned[1]) - def test_invalid_input_1(self): ns = Namespace(user_assigned=["random_input"]) with self.assertRaises(InvalidArgumentValueError) as context: validate_app_force_set_user_identity_or_warning(ns) self.assertTrue('Allowed values for "user-assigned" are:' in str(context.exception)) - def test_invalid_input_2(self): ns = Namespace(user_assigned=["ua1", "ua2"]) with self.assertRaises(InvalidArgumentValueError) as context: diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_remove.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_remove.py index 0b9786ba237..09567b47a85 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_remove.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_remove.py @@ -20,7 +20,6 @@ def test_get_new_identity_type_for_remove_for_type_none_1(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.NONE) - def test_get_new_identity_type_for_remove_for_type_none_2(self): exist_identity_type = ManagedIdentityType.NONE is_remove_system_identity = True @@ -42,7 +41,6 @@ def test_get_new_identity_type_for_remove_for_system_assigned_1(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.SYSTEM_ASSIGNED) - def test_get_new_identity_type_for_remove_for_system_assigned_2(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED is_remove_system_identity = True @@ -52,7 +50,6 @@ def test_get_new_identity_type_for_remove_for_system_assigned_2(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.NONE) - def test_get_new_identity_type_for_remove_for_system_assigned_3(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED is_remove_system_identity = False @@ -62,7 +59,6 @@ def test_get_new_identity_type_for_remove_for_system_assigned_3(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.SYSTEM_ASSIGNED) - def test_get_new_identity_type_for_remove_for_system_assigned_4(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED is_remove_system_identity = True @@ -72,7 +68,6 @@ def test_get_new_identity_type_for_remove_for_system_assigned_4(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.NONE) - def test_get_new_identity_type_for_remove_for_system_assigned_5(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED is_remove_system_identity = None @@ -94,7 +89,6 @@ def test_get_new_identity_type_for_remove_for_user_assigned_1(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.NONE) - def test_get_new_identity_type_for_remove_for_user_assigned_2(self): exist_identity_type = ManagedIdentityType.USER_ASSIGNED is_remove_system_identity = False @@ -104,7 +98,6 @@ def test_get_new_identity_type_for_remove_for_user_assigned_2(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.NONE) - def test_get_new_identity_type_for_remove_for_user_assigned_3(self): exist_identity_type = ManagedIdentityType.USER_ASSIGNED is_remove_system_identity = None @@ -114,7 +107,6 @@ def test_get_new_identity_type_for_remove_for_user_assigned_3(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.NONE) - def test_get_new_identity_type_for_remove_for_user_assigned_4(self): exist_identity_type = ManagedIdentityType.USER_ASSIGNED is_remove_system_identity = True @@ -124,7 +116,6 @@ def test_get_new_identity_type_for_remove_for_user_assigned_4(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.USER_ASSIGNED) - def test_get_new_identity_type_for_remove_for_user_assigned_5(self): exist_identity_type = ManagedIdentityType.USER_ASSIGNED is_remove_system_identity = False @@ -134,7 +125,6 @@ def test_get_new_identity_type_for_remove_for_user_assigned_5(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.USER_ASSIGNED) - def test_get_new_identity_type_for_remove_for_user_assigned_6(self): exist_identity_type = ManagedIdentityType.USER_ASSIGNED is_remove_system_identity = None @@ -156,7 +146,6 @@ def test_get_new_identity_type_for_remove_for_both_assigned_1(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.NONE) - def test_get_new_identity_type_for_remove_for_both_assigned_2(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED is_remove_system_identity = False @@ -166,7 +155,6 @@ def test_get_new_identity_type_for_remove_for_both_assigned_2(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.SYSTEM_ASSIGNED) - def test_get_new_identity_type_for_remove_for_both_assigned_3(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED is_remove_system_identity = None @@ -176,7 +164,6 @@ def test_get_new_identity_type_for_remove_for_both_assigned_3(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.SYSTEM_ASSIGNED) - def test_get_new_identity_type_for_remove_for_both_assigned_4(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED is_remove_system_identity = True @@ -186,7 +173,6 @@ def test_get_new_identity_type_for_remove_for_both_assigned_4(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.USER_ASSIGNED) - def test_get_new_identity_type_for_remove_for_both_assigned_5(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED is_remove_system_identity = False @@ -196,7 +182,6 @@ def test_get_new_identity_type_for_remove_for_both_assigned_5(self): new_user_identities) self.assertEqual(new_identity_type, ManagedIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED) - def test_get_new_identity_type_for_remove_for_both_assigned_6(self): exist_identity_type = ManagedIdentityType.SYSTEM_ASSIGNED_USER_ASSIGNED is_remove_system_identity = None diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py index e3716394918..a8a3c834473 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_scenario.py @@ -63,7 +63,7 @@ def test_app_identity_crud(self): self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) - self.assertTrue(type(user_identity_dict) == dict) + self.assertTrue(isinstance(user_identity_dict, dict)) self.assertTrue(self._contains_user_id_1(user_identity_dict.keys())) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) @@ -74,7 +74,7 @@ def test_app_identity_crud(self): self.exists('identity.userAssignedIdentities') ]).json_value user_identity_dict = self._to_lower(app['identity']['userAssignedIdentities']) - self.assertTrue(type(user_identity_dict) == dict) + self.assertTrue(isinstance(user_identity_dict, dict)) self.assertTrue(len(user_identity_dict) == 1) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) @@ -102,15 +102,12 @@ def test_app_identity_crud(self): self.cmd('spring app identity remove -n {app} -g {rg} -s {serviceName} --system-assigned --user-assigned {ua1} {ua2}', checks=[self.check('identity', None)]) - def _contains_user_id_1(self, keys): return MASKED_USER_IDENTITY_RESOURCE_ID_1.lower() in keys or USER_IDENTITY_RESOURCE_ID_1.lower() in keys - def _contains_user_id_2(self, keys): return MASKED_USER_IDENTITY_RESOURCE_ID_2.lower() in keys or USER_IDENTITY_RESOURCE_ID_2.lower() in keys - def _to_lower(self, str_dict): new_dict = {} for key in str_dict.keys(): diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_validator.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_validator.py index 65e7270796a..52a9b147f0a 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_validator.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_app_managed_identity_validator.py @@ -22,7 +22,6 @@ def test_invalid_user_identity_resource_id(self): validate_app_identity_remove_or_warning(ns) self.assertTrue("Invalid user-assigned managed identity resource ID" in str(context.exception)) - def test_invalid_user_identities(self): fake_id = FAKE_USER_IDENTITY_RESOURCE_ID user_assigned = set(fake_id) @@ -43,7 +42,6 @@ def test_scope_and_role_not_used_together_1(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Parameter \"role\" and \"scope\" should be used together." in str(context.exception)) - def test_scope_and_role_not_used_together_2(self): ns = Namespace( role=None, @@ -54,7 +52,6 @@ def test_scope_and_role_not_used_together_2(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Parameter \"role\" and \"scope\" should be used together." in str(context.exception)) - def test_scope_and_role_not_used_together_3(self): ns = Namespace( role="fake-role", @@ -65,7 +62,6 @@ def test_scope_and_role_not_used_together_3(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Parameter \"role\" and \"scope\" should be used together." in str(context.exception)) - def test_scope_and_role_not_used_together_4(self): ns = Namespace( role="fake-role", @@ -76,7 +72,6 @@ def test_scope_and_role_not_used_together_4(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Parameter \"role\" and \"scope\" should be used together." in str(context.exception)) - def test_scope_and_role_not_used_together_5(self): ns = Namespace( role=None, @@ -87,7 +82,6 @@ def test_scope_and_role_not_used_together_5(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Parameter \"role\" and \"scope\" should be used together." in str(context.exception)) - def test_scope_and_role_not_used_together_6(self): ns = Namespace( role=None, @@ -98,7 +92,6 @@ def test_scope_and_role_not_used_together_6(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Parameter \"role\" and \"scope\" should be used together." in str(context.exception)) - def test_scope_and_role_without_system_identity_but_with_user_identity_1(self): ns = Namespace( role="fake-role", @@ -109,7 +102,6 @@ def test_scope_and_role_without_system_identity_but_with_user_identity_1(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Invalid to use parameter \"role\" and \"scope\" with \"user-assigned\" parameter." in str(context.exception)) - def test_scope_and_role_without_system_identity_but_with_user_identity_2(self): ns = Namespace( role="fake-role", @@ -120,7 +112,6 @@ def test_scope_and_role_without_system_identity_but_with_user_identity_2(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Invalid to use parameter \"role\" and \"scope\" with \"user-assigned\" parameter." in str(context.exception)) - def test_invalid_user_identity_resource_id_1(self): ns = Namespace( role=None, @@ -131,7 +122,6 @@ def test_invalid_user_identity_resource_id_1(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Invalid user-assigned managed identity resource ID" in str(context.exception)) - def test_invalid_user_identity_resource_id_2(self): ns = Namespace( role=None, @@ -142,7 +132,6 @@ def test_invalid_user_identity_resource_id_2(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Invalid user-assigned managed identity resource ID" in str(context.exception)) - def test_invalid_user_identity_resource_id_3(self): ns = Namespace( role=None, @@ -153,7 +142,6 @@ def test_invalid_user_identity_resource_id_3(self): validate_app_identity_assign_or_warning(ns) self.assertTrue("Invalid user-assigned managed identity resource ID" in str(context.exception)) - def test_invalid_user_identity_resource_id_4(self): ns = Namespace( role=None, diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_both_identity_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_both_identity_scenario.py index 59ddea22ba8..c8310efa890 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_both_identity_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_both_identity_scenario.py @@ -54,15 +54,12 @@ def test_create_app_with_both_identity(self): self.assertTrue(self._contains_user_id_1(user_identity_dict.keys())) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) - def _contains_user_id_1(self, keys): return MASKED_USER_IDENTITY_RESOURCE_ID_1.lower() in keys or USER_IDENTITY_RESOURCE_ID_1.lower() in keys - def _contains_user_id_2(self, keys): return MASKED_USER_IDENTITY_RESOURCE_ID_2.lower() in keys or USER_IDENTITY_RESOURCE_ID_2.lower() in keys - def _to_lower(self, str_dict): new_dict = {} for key in str_dict.keys(): diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_managed_identity_validator.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_managed_identity_validator.py index ed958b47c48..5ba7b52937a 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_managed_identity_validator.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_managed_identity_validator.py @@ -21,21 +21,18 @@ def test_system_identity_override_1(self): validate_create_app_with_system_identity_or_warning(ns) self.assertEquals(ns.system_assigned, False) - def test_system_identity_override_2(self): ns = Namespace(system_assigned=None, assign_identity=True) validate_create_app_with_system_identity_or_warning(ns) self.assertEquals(ns.system_assigned, True) - def test_system_identity_override_3(self): ns = Namespace(system_assigned=True, assign_identity=None) validate_create_app_with_system_identity_or_warning(ns) self.assertEquals(ns.system_assigned, True) - def test_system_identity_override_4(self): ns = Namespace(system_assigned=False, assign_identity=None) @@ -50,25 +47,21 @@ def test_conflict_parameter_1(self): assign_identity=None) validate_create_app_with_system_identity_or_warning(ns) - def test_conflict_parameter_2(self): ns = Namespace(system_assigned=False, assign_identity=None) validate_create_app_with_system_identity_or_warning(ns) - def test_conflict_parameter_3(self): ns = Namespace(system_assigned=True, assign_identity=None) validate_create_app_with_system_identity_or_warning(ns) - def test_conflict_parameter_4(self): ns = Namespace(system_assigned=None, assign_identity=False) validate_create_app_with_system_identity_or_warning(ns) - def test_conflict_parameter_5(self): ns = Namespace(system_assigned=False, assign_identity=False) @@ -76,7 +69,6 @@ def test_conflict_parameter_5(self): validate_create_app_with_system_identity_or_warning(ns) self.assertTrue('Parameter "system-assigned" should not use together with "assign-identity".' in str(context.exception)) - def test_conflict_parameter_6(self): ns = Namespace(system_assigned=True, assign_identity=False) @@ -84,13 +76,11 @@ def test_conflict_parameter_6(self): validate_create_app_with_system_identity_or_warning(ns) self.assertTrue('Parameter "system-assigned" should not use together with "assign-identity".' in str(context.exception)) - def test_conflict_parameter_7(self): ns = Namespace(system_assigned=None, assign_identity=True) validate_create_app_with_system_identity_or_warning(ns) - def test_conflict_parameter_8(self): ns = Namespace(system_assigned=False, assign_identity=True) @@ -98,7 +88,6 @@ def test_conflict_parameter_8(self): validate_create_app_with_system_identity_or_warning(ns) self.assertTrue('Parameter "system-assigned" should not use together with "assign-identity".' in str(context.exception)) - def test_conflict_parameter_9(self): ns = Namespace(system_assigned=True, assign_identity=True) @@ -113,12 +102,10 @@ def test_user_identity_resource_id_1(self): ns = Namespace(user_assigned=None) validate_create_app_with_user_identity_or_warning(ns) - def test_user_identity_resource_id_2(self): ns = Namespace(user_assigned=[FAKE_USER_IDENTITY_RESOURCE_ID]) validate_create_app_with_user_identity_or_warning(ns) - def test_user_identity_resource_id_3(self): ns = Namespace(user_assigned=["ua1"]) with self.assertRaises(InvalidArgumentValueError) as context: diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_system_identity_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_system_identity_scenario.py index 1cf33a3a548..be6bb3aedcd 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_system_identity_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_system_identity_scenario.py @@ -25,7 +25,6 @@ def test_create_app_with_assign_identity(self): self.check('identity.userAssignedIdentities', None) ]) - def test_create_app_with_system_assigned(self): self.kwargs.update({ 'app': 'create-app-system-identity-2', diff --git a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_user_identity_scenario.py b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_user_identity_scenario.py index 86fccbf81a2..28f2ea74749 100644 --- a/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_user_identity_scenario.py +++ b/src/spring/azext_spring/tests/latest/app_managed_identity/test_create_app_with_user_identity_scenario.py @@ -54,15 +54,12 @@ def test_create_app_with_user_identity(self): self.assertTrue(self._contains_user_id_1(user_identity_dict.keys())) self.assertTrue(self._contains_user_id_2(user_identity_dict.keys())) - def _contains_user_id_1(self, keys): return MASKED_USER_IDENTITY_RESOURCE_ID_1.lower() in keys or USER_IDENTITY_RESOURCE_ID_1.lower() in keys - def _contains_user_id_2(self, keys): return MASKED_USER_IDENTITY_RESOURCE_ID_2.lower() in keys or USER_IDENTITY_RESOURCE_ID_2.lower() in keys - def _to_lower(self, str_dict): new_dict = {} for key in str_dict.keys(): diff --git a/src/spring/azext_spring/tests/latest/custom_preparers.py b/src/spring/azext_spring/tests/latest/custom_preparers.py index af7ce985032..8b5f16063b0 100644 --- a/src/spring/azext_spring/tests/latest/custom_preparers.py +++ b/src/spring/azext_spring/tests/latest/custom_preparers.py @@ -63,7 +63,7 @@ def __init__(self, dev_setting_name, moniker): class SpringResourceGroupPreparer(ResourceGroupPreparer): def __init__(self, location='uksouth', **kwargs): super(SpringResourceGroupPreparer, self).__init__(location=location, **kwargs) - + def create_resource(self, name, **kwargs): response = super().create_resource(name, **kwargs) is_live = self.live_test or self.test_class_instance.in_recording diff --git a/src/spring/azext_spring/tests/latest/test_asa_accelerator.py b/src/spring/azext_spring/tests/latest/test_asa_accelerator.py index 65e28eddca4..5d2b8de04dc 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_accelerator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_accelerator.py @@ -10,8 +10,8 @@ # pylint: disable=line-too-long # pylint: disable=too-many-lines ''' -Since the scenarios covered here depend on a Azure Spring service instance creation. -It cannot support live run. So mark it as record_only. +Since the scenarios covered here depend on a Azure Spring service instance creation. +It cannot support live run. So mark it as record_only. ''' @@ -20,7 +20,6 @@ class ApidAcceleratorTest(ScenarioTest): @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) def test_predefined_accelerator(self, resource_group, spring): - self.kwargs.update({ 'serviceName': spring, 'rg': resource_group, @@ -55,7 +54,6 @@ def test_predefined_accelerator(self, resource_group, spring): @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) def test_customized_accelerator(self, resource_group, spring): - self.kwargs.update({ 'serviceName': spring, 'rg': resource_group, @@ -91,7 +89,6 @@ def test_customized_accelerator(self, resource_group, spring): @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) def test_customized_accelerator_of_fragment_type(self, resource_group, spring): - self.kwargs.update({ 'serviceName': spring, 'rg': resource_group, diff --git a/src/spring/azext_spring/tests/latest/test_asa_api_portal.py b/src/spring/azext_spring/tests/latest/test_asa_api_portal.py index 0406ef67c1f..d46444928c8 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_api_portal.py +++ b/src/spring/azext_spring/tests/latest/test_asa_api_portal.py @@ -43,7 +43,7 @@ def __init__(self, def create_resource(self, *_, **kwargs): self.resource_group = self._get_resource_group(**kwargs) self.spring = self._get_spring(**kwargs) - + def remove_resource(self, *_, **__): self.live_only_execute(self.cli_ctx, 'spring api-portal delete -g {} -s {} --yes'.format(self.resource_group, self.spring)) self.live_only_execute(self.cli_ctx, 'spring api-portal create -g {} -s {}'.format(self.resource_group, self.spring)) @@ -57,7 +57,6 @@ class ApiPortalTest(ScenarioTest): @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) @ApiPortalWrapper() def test_api_portal(self, resource_group, spring, sp_name, sp_password): - self.kwargs.update({ 'serviceName': spring, 'rg': resource_group, @@ -170,7 +169,7 @@ def _get_cert(*_, **__): 'asa', 'my-domain.microsoft.com', 'my-cert') - + def test_custom_domain_unbind(self): client = _get_basic_mock_client() api_portal_custom_domain_unbind(_get_test_cmd(), diff --git a/src/spring/azext_spring/tests/latest/test_asa_app.py b/src/spring/azext_spring/tests/latest/test_asa_app.py index dffcaf9cf3d..17db0394eb4 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app.py @@ -360,7 +360,7 @@ def test_app_deploy_waiting_enterprise(self, file_mock): self.assertEqual('BuildResult', resource.properties.source.type) self.assertEqual(self.result_id, resource.properties.source.build_result_id) self.assertIsNone(resource.properties.source.version) - + @mock.patch('azext_spring._deployment_uploadable_factory.FileUpload.upload_and_build') def test_app_deploy_failed_enterprise(self, file_mock): file_mock.return_value = mock.MagicMock() diff --git a/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py b/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py index 7c0b5568f49..016b3636ded 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py +++ b/src/spring/azext_spring/tests/latest/test_asa_application_accelerator.py @@ -47,8 +47,8 @@ def _mock_dev_tool_portal(enable_accelerator): resource = models.DevToolPortalResource.deserialize(json.loads('{"properties":{"provisioningState": "Succeeded"}}')) resource.properties.features = models.DevToolPortalFeatureSettings( application_accelerator=models.DevToolPortalFeatureDetail( - state=models.DevToolPortalFeatureState.ENABLED if enable_accelerator \ - else models.DevToolPortalFeatureState.DISABLED)) + state=models.DevToolPortalFeatureState.ENABLED if enable_accelerator + else models.DevToolPortalFeatureState.DISABLED)) return resource @@ -64,14 +64,14 @@ class ApplicationAccelerator(unittest.TestCase): def __init__(self, methodName: str = ...): super().__init__(methodName=methodName) self.created_resource = None - self.dev_tool_portal =None + self.dev_tool_portal = None self.deleted = False - + def setUp(self): resp = super().setUp() free_mock_client.reset_mock() return resp - + # @mock.patch('azext_spring._utils.cf_resource_groups', _cf_resource_group) def _execute(self, method, cmd, client, *kwargs): client = client or _get_basic_mock_client() @@ -125,6 +125,7 @@ def test_asa_acc_delete_configure_dev_tool_portal_wait(self): self.assertEqual(models.DevToolPortalFeatureState.DISABLED, self.dev_tool_portal.properties.features.application_accelerator.state) + ''' Since the scenarios covered here depend on a Azure Spring service instance creation. It cannot support live run. So mark it as record_only. @@ -136,7 +137,6 @@ class ApiApplicationAcceleratorTest(ScenarioTest): @SpringResourceGroupPreparer(dev_setting_name=SpringTestEnvironmentEnum.ENTERPRISE['resource_group_name']) @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE['spring']) def test_application_accelerator(self, resource_group, spring): - self.kwargs.update({ 'serviceName': spring, 'rg': resource_group diff --git a/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py b/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py index 5fb00b96329..c79509e462a 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py +++ b/src/spring/azext_spring/tests/latest/test_asa_application_configuration_service.py @@ -26,7 +26,7 @@ def __init__(self, def create_resource(self, *_, **kwargs): self.resource_group = self._get_resource_group(**kwargs) self.spring = self._get_spring(**kwargs) - + def remove_resource(self, *_, **__): self.live_only_execute(self.cli_ctx, 'spring application-configuration-service delete -g {} -s {} --yes'.format(self.resource_group, self.spring)) self.live_only_execute(self.cli_ctx, 'spring application-configuration-service create -g {} -s {}'.format(self.resource_group, self.spring)) @@ -39,7 +39,6 @@ class ApplicationConfigurationServiceTest(ScenarioTest): @SpringAppNamePreparer() @TearDown() def test_application_configuration_service(self, resource_group, spring, app): - self.kwargs.update({ 'serviceName': spring, 'rg': resource_group, @@ -49,7 +48,7 @@ def test_application_configuration_service(self, resource_group, spring, app): "uri": "https://github.com/spring-petclinic/spring-petclinic-microservices-config", "app": app }) - + self.cmd('spring app create -g {rg} -s {serviceName} -n {app}') self.cmd('spring application-configuration-service show -g {rg} -s {serviceName}', checks=[ @@ -70,7 +69,7 @@ def test_application_configuration_service(self, resource_group, spring, app): result = self.cmd('spring application-configuration-service git repo list -g {rg} -s {serviceName}').get_output_in_json() self.assertTrue(len(result) > 0) - + self.cmd('spring application-configuration-service git repo remove --name {repo} -g {rg} -s {serviceName}') result = self.cmd('spring application-configuration-service git repo list -g {rg} -s {serviceName}').get_output_in_json() self.assertTrue(len(result) == 0) diff --git a/src/spring/azext_spring/tests/latest/test_asa_application_live_view.py b/src/spring/azext_spring/tests/latest/test_asa_application_live_view.py index 9a954879210..f31f822c655 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_application_live_view.py +++ b/src/spring/azext_spring/tests/latest/test_asa_application_live_view.py @@ -46,10 +46,11 @@ def _mock_dev_tool_portal(enable_live_view): resource = models.DevToolPortalResource.deserialize(json.loads('{"properties":{"provisioningState": "Succeeded"}}')) resource.properties.features = models.DevToolPortalFeatureSettings( application_live_view=models.DevToolPortalFeatureDetail( - state=models.DevToolPortalFeatureState.ENABLED if enable_live_view \ - else models.DevToolPortalFeatureState.DISABLED)) + state=models.DevToolPortalFeatureState.ENABLED if enable_live_view else + models.DevToolPortalFeatureState.DISABLED)) return resource + def _mock_enabled_get_dev_tool_portal(*_): return _mock_dev_tool_portal(enable_live_view=True) @@ -66,12 +67,12 @@ def __init__(self, methodName: str = ...): self.deleted = False self.created_alv_request = None self.dev_tool_portal_request = None - + def setUp(self): resp = super().setUp() free_mock_client.reset_mock() return resp - + # @mock.patch('azext_spring._utils.cf_resource_groups', _cf_resource_group) def _execute(self, method, cmd, client, *kwargs): client = client or _get_basic_mock_client() diff --git a/src/spring/azext_spring/tests/latest/test_asa_buildpack_binding.py b/src/spring/azext_spring/tests/latest/test_asa_buildpack_binding.py index 91a265c0155..bada3da0601 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_buildpack_binding.py +++ b/src/spring/azext_spring/tests/latest/test_asa_buildpack_binding.py @@ -3,7 +3,6 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -import os from azure.cli.testsdk import (ScenarioTest) from azure.cli.testsdk.reverse_dependency import ( get_dummy_cli, @@ -41,8 +40,6 @@ class BuildpackBindingTest(ScenarioTest): @SpringPreparer(**SpringTestEnvironmentEnum.ENTERPRISE_WITH_TANZU['spring']) @TearDown() def test_buildpack_binding(self, resource_group, spring): - py_path = os.path.abspath(os.path.dirname(__file__)) - self.kwargs.update({ 'serviceName': spring, 'rg': resource_group, diff --git a/src/spring/azext_spring/tests/latest/test_asa_create.py b/src/spring/azext_spring/tests/latest/test_asa_create.py index f8ba2f333d0..1773a938619 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_create.py +++ b/src/spring/azext_spring/tests/latest/test_asa_create.py @@ -265,9 +265,9 @@ def test_asc_create_with_application_insights_default(self): self.assertEqual('Enterprise', resource.sku.tier) self.assertEqual('ApplicationInsights', self.buildpack_binding_resource.properties.binding_type) self.assertEqual('fake-create-connection-string', - self.buildpack_binding_resource.properties.launch_properties.properties['connection-string']) + self.buildpack_binding_resource.properties.launch_properties.properties['connection-string']) self.assertEqual(10, - self.buildpack_binding_resource.properties.launch_properties.properties['sampling-percentage']) + self.buildpack_binding_resource.properties.launch_properties.properties['sampling-percentage']) def test_asc_create_with_application_insights_key(self): self._execute('rg', 'asc', sku=self._get_sku('Enterprise'), app_insights_key='test-application-insights-key', sampling_rate=23) @@ -276,9 +276,9 @@ def test_asc_create_with_application_insights_key(self): self.assertEqual('Enterprise', resource.sku.tier) self.assertEqual('ApplicationInsights', self.buildpack_binding_resource.properties.binding_type) self.assertEqual('test-application-insights-key', - self.buildpack_binding_resource.properties.launch_properties.properties['connection-string']) + self.buildpack_binding_resource.properties.launch_properties.properties['connection-string']) self.assertEqual(23, - self.buildpack_binding_resource.properties.launch_properties.properties['sampling-percentage']) + self.buildpack_binding_resource.properties.launch_properties.properties['sampling-percentage']) def test_asc_create_with_application_insights_name(self): self._execute('rg', 'asc', sku=self._get_sku('Enterprise'), app_insights='test-application-insights', sampling_rate=53) @@ -287,9 +287,9 @@ def test_asc_create_with_application_insights_name(self): self.assertEqual('Enterprise', resource.sku.tier) self.assertEqual('ApplicationInsights', self.buildpack_binding_resource.properties.binding_type) self.assertEqual('fake-get-connection-string', - self.buildpack_binding_resource.properties.launch_properties.properties['connection-string']) + self.buildpack_binding_resource.properties.launch_properties.properties['connection-string']) self.assertEqual(53, - self.buildpack_binding_resource.properties.launch_properties.properties['sampling-percentage']) + self.buildpack_binding_resource.properties.launch_properties.properties['sampling-percentage']) class TestSpringAppCreateWithIngressConfig(BasicTest): From 5e51adddfec4ab8ee782233edc46d1fba6281333 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Mon, 18 Dec 2023 08:38:33 +0800 Subject: [PATCH 14/19] Fix style errors --- .../azext_spring/tests/latest/custom_recording_processor.py | 2 +- src/spring/azext_spring/tests/latest/test_asa_app.py | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/spring/azext_spring/tests/latest/custom_recording_processor.py b/src/spring/azext_spring/tests/latest/custom_recording_processor.py index 3649c3e35e7..3a1f01bbbb6 100644 --- a/src/spring/azext_spring/tests/latest/custom_recording_processor.py +++ b/src/spring/azext_spring/tests/latest/custom_recording_processor.py @@ -43,5 +43,5 @@ def process_response(self, response): class SpringTestEndpointReplacer(RegexSingleValueReplacer): def __init__(self): - super(SpringTestEndpointReplacer, self).__init__(re.compile(f'(?<="primaryKey":")[^"]+|(?<="secondaryKey":")[^"]+|(?<="primaryTestEndpoint":")[^"]+|(?<="secondaryTestEndpoint":")[^"]+', re.IGNORECASE), + super(SpringTestEndpointReplacer, self).__init__(re.compile('(?<="primaryKey":")[^"]+|(?<="secondaryKey":")[^"]+|(?<="primaryTestEndpoint":")[^"]+|(?<="secondaryTestEndpoint":")[^"]+', re.IGNORECASE), 'primary', 'fake') diff --git a/src/spring/azext_spring/tests/latest/test_asa_app.py b/src/spring/azext_spring/tests/latest/test_asa_app.py index 17db0394eb4..6dd86c4aafc 100644 --- a/src/spring/azext_spring/tests/latest/test_asa_app.py +++ b/src/spring/azext_spring/tests/latest/test_asa_app.py @@ -699,16 +699,16 @@ def test_app_create_in_enterprise(self): def test_app_with_large_instance_count_enterprise(self): client = self._get_basic_mock_client(sku='Enterprise') - with self.assertRaisesRegexp(CLIError, 'Invalid --instance-count, should be in range \[1, 1000\]'): + with self.assertRaisesRegexp(CLIError, r'Invalid --instance-count, should be in range \[1, 1000\]'): self._execute('rg', 'asc', 'app', cpu='500m', memory='2Gi', instance_count=1001, client=client) def test_app_with_large_instance_count(self): - with self.assertRaisesRegexp(CLIError, 'Invalid --instance-count, should be in range \[1, 500\]'): + with self.assertRaisesRegexp(CLIError, r'Invalid --instance-count, should be in range \[1, 500\]'): self._execute('rg', 'asc', 'app', cpu='500m', memory='2Gi', instance_count=501) def test_app_with_large_instance_count_basic(self): client = self._get_basic_mock_client(sku='Basic') - with self.assertRaisesRegexp(CLIError, 'Invalid --instance-count, should be in range \[1, 25\]'): + with self.assertRaisesRegexp(CLIError, r'Invalid --instance-count, should be in range \[1, 25\]'): self._execute('rg', 'asc', 'app', cpu='500m', memory='2Gi', instance_count=26, client=client) def test_app_with_persistent_storage_enterprise(self): From 5c67ae63b8c24c66fcd31b3b0b08e8bf949485f6 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Mon, 18 Dec 2023 08:47:56 +0800 Subject: [PATCH 15/19] Fix style errors --- src/spring/azext_spring/_utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/spring/azext_spring/_utils.py b/src/spring/azext_spring/_utils.py index e0e2cfe3ad1..ff26e6eb95b 100644 --- a/src/spring/azext_spring/_utils.py +++ b/src/spring/azext_spring/_utils.py @@ -207,7 +207,7 @@ def get_azure_files_info(file_sas_url): def _get_azure_storage_client_info(account_type, sas_url): - regex = compile("http(s)?://(?P.*?)\.{0}\.(?P.*?)/(?P.*?)/(?P.*?)\?(?P.*)".format(account_type)) + regex = compile(r"http(s)?://(?P.*?)\.{0}\.(?P.*?)/(?P.*?)/(?P.*?)\?(?P.*)".format(account_type)) matchObj = search(regex, sas_url) account_name = matchObj.group('account_name') endpoint_suffix = matchObj.group('endpoint_suffix') From 7b01a257ab77a0eaa87bd0c1df903c5e0e760a0f Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Mon, 18 Dec 2023 14:27:14 +0800 Subject: [PATCH 16/19] Fix style errors - C0301 --- src/spring/azext_spring/_app_factory.py | 19 ++++---- .../_app_managed_identity_validator.py | 30 ++++++++---- src/spring/azext_spring/_build_service.py | 38 +++++++++------ .../_deployment_source_factory.py | 2 +- .../_deployment_uploadable_factory.py | 3 +- src/spring/azext_spring/_marketplace.py | 3 +- src/spring/azext_spring/_tanzu_component.py | 18 +++++-- src/spring/azext_spring/_utils.py | 16 +++++-- src/spring/azext_spring/_validators.py | 47 ++++++++++++------- src/spring/azext_spring/api_portal.py | 3 +- .../azext_spring/app_managed_identity.py | 9 ++-- .../azext_spring/application_accelerator.py | 27 +++++++---- src/spring/azext_spring/buildpack_binding.py | 2 + src/spring/azext_spring/custom.py | 4 +- src/spring/azext_spring/gateway.py | 24 ++++++---- src/spring/azext_spring/spring_instance.py | 6 ++- 16 files changed, 167 insertions(+), 84 deletions(-) diff --git a/src/spring/azext_spring/_app_factory.py b/src/spring/azext_spring/_app_factory.py index f4199420fd1..65b4193f4b3 100644 --- a/src/spring/azext_spring/_app_factory.py +++ b/src/spring/azext_spring/_app_factory.py @@ -114,13 +114,14 @@ def _load_custom_persistent_disks(self, client, resource_group, service, sku, pe storage_resource = client.storages.get(resource_group, service, item['storageName']) storage_id = storage_resource.id + custom_props = item['customPersistentDiskProperties'] custom_persistent_disk_properties = models.AzureFileVolume( - type=item['customPersistentDiskProperties']['type'], - share_name=item['customPersistentDiskProperties']['shareName'] if 'shareName' in item['customPersistentDiskProperties'] else None, - mount_path=item['customPersistentDiskProperties']['mountPath'], - mount_options=item['customPersistentDiskProperties']['mountOptions'] if 'mountOptions' in item['customPersistentDiskProperties'] else None, - read_only=item['customPersistentDiskProperties']['readOnly'] if 'readOnly' in item['customPersistentDiskProperties'] else None, - enable_sub_path=item['customPersistentDiskProperties']['enableSubPath'] if 'enableSubPath' in item['customPersistentDiskProperties'] else None) + type=custom_props['type'], + share_name=custom_props['shareName'] if 'shareName' in custom_props else None, + mount_path=custom_props['mountPath'], + mount_options=custom_props['mountOptions'] if 'mountOptions' in custom_props else None, + read_only=custom_props['readOnly'] if 'readOnly' in custom_props else None, + enable_sub_path=custom_props['enableSubPath'] if 'enableSubPath' in custom_props else None) custom_persistent_disks.append( models.CustomPersistentDiskResource( @@ -136,7 +137,8 @@ def _load_vnet_addons(self, public_for_vnet=None, **_): else: return None - def _load_ingress_settings(self, ingress_read_timeout=None, ingress_send_timeout=None, session_affinity=None, session_max_age=None, backend_protocol=None, client_auth_certs=None, **_): + def _load_ingress_settings(self, ingress_read_timeout=None, ingress_send_timeout=None, session_affinity=None, + session_max_age=None, backend_protocol=None, client_auth_certs=None, **_): if (ingress_read_timeout is not None) or (ingress_send_timeout is not None) or \ (session_affinity is not None) or (session_max_age is not None) or (backend_protocol is not None) or \ (client_auth_certs is not None): @@ -197,7 +199,8 @@ def _get_persistent_disk_size(self, enable_persistent_storage, **_): class EnterpriseTierApp(DefaultApp): def _get_persistent_disk_size(self, enable_persistent_storage, **_): if enable_persistent_storage: - raise InvalidArgumentValueError('Enterprise tier Spring instance does not support --enable-persistent-storage') + raise InvalidArgumentValueError('Enterprise tier Spring instance does not support ' + '--enable-persistent-storage') def app_selector(sku, **_): diff --git a/src/spring/azext_spring/_app_managed_identity_validator.py b/src/spring/azext_spring/_app_managed_identity_validator.py index 3263b2388e6..3a70485033d 100644 --- a/src/spring/azext_spring/_app_managed_identity_validator.py +++ b/src/spring/azext_spring/_app_managed_identity_validator.py @@ -12,9 +12,14 @@ logger = get_logger(__name__) -OBSOLETE_APP_IDENTITY_REMOVE = "Remove managed identities without \"system-assigned\" or \"user-assigned\" parameters is obsolete, will only remove system-assigned managed identity, and will not be supported in a future release." -WARNING_NO_USER_IDENTITY_RESOURCE_ID = "No resource ID of user-assigned managed identity is given for parameter \"user-assigned\", will remove ALL user-assigned managed identities." -OBSOLETE_APP_IDENTITY_ASSIGN = "Assign managed identities without \"system-assigned\" or \"user-assigned\" parameters is obsolete, will only enable system-assigned managed identity, and will not be supported in a future release." +OBSOLETE_APP_IDENTITY_REMOVE = ("Remove managed identities without \"system-assigned\" or \"user-assigned\" " + "parameters is obsolete, will only remove system-assigned managed identity, " + "and will not be supported in a future release.") +WARNING_NO_USER_IDENTITY_RESOURCE_ID = ("No resource ID of user-assigned managed identity is given for parameter " + "\"user-assigned\", will remove ALL user-assigned managed identities.") +OBSOLETE_APP_IDENTITY_ASSIGN = ("Assign managed identities without \"system-assigned\" or \"user-assigned\" " + "parameters is obsolete, will only enable system-assigned managed identity, " + "and will not be supported in a future release.") ENABLE_LOWER = "enable" DISABLE_LOWER = "disable" @@ -24,14 +29,16 @@ def validate_app_identity_remove_or_warning(namespace): logger.warning(OBSOLETE_APP_IDENTITY_REMOVE) if namespace.user_assigned is not None: if not isinstance(namespace.user_assigned, list): - raise InvalidArgumentValueError("Parameter value for \"user-assigned\" should be empty or a list of space-separated managed identity resource ID.") + raise InvalidArgumentValueError("Parameter value for \"user-assigned\" should be empty " + "or a list of space-separated managed identity resource ID.") if len(namespace.user_assigned) == 0: logger.warning(WARNING_NO_USER_IDENTITY_RESOURCE_ID) namespace.user_assigned = _normalized_user_identitiy_resource_id_list(namespace.user_assigned) for resource_id in namespace.user_assigned: is_valid = _is_valid_user_assigned_managed_identity_resource_id(resource_id) if not is_valid: - raise InvalidArgumentValueError("Invalid user-assigned managed identity resource ID \"{}\".".format(resource_id)) + error_msg_template = "Invalid user-assigned managed identity resource ID \"{}\"." + raise InvalidArgumentValueError(error_msg_template.format(resource_id)) def _normalized_user_identitiy_resource_id_list(user_identity_resource_id_list): @@ -71,7 +78,8 @@ def _validate_role_and_scope_should_use_together(namespace): def _validate_role_and_scope_should_not_use_with_user_identity(namespace): if _has_role_and_scope(namespace) and _only_has_user_assigned(namespace): - raise InvalidArgumentValueError("Invalid to use parameter \"role\" and \"scope\" with \"user-assigned\" parameter.") + raise InvalidArgumentValueError("Invalid to use parameter \"role\" and \"scope\" " + "with \"user-assigned\" parameter.") def _has_role_and_scope(namespace): @@ -90,7 +98,8 @@ def _validate_user_identity_resource_id(namespace): if namespace.user_assigned: for resource_id in namespace.user_assigned: if not _is_valid_user_assigned_managed_identity_resource_id(resource_id): - raise InvalidArgumentValueError("Invalid user-assigned managed identity resource ID \"{}\".".format(resource_id)) + error_msg_template = "Invalid user-assigned managed identity resource ID \"{}\"." + raise InvalidArgumentValueError(error_msg_template.format(resource_id)) def _normalize_user_identity_resource_id(namespace): @@ -118,7 +127,8 @@ def validate_app_force_set_system_identity_or_warning(namespace): raise InvalidArgumentValueError('Parameter "system-assigned" expected at least one argument.') namespace.system_assigned = namespace.system_assigned.strip().lower() if namespace.system_assigned.strip().lower() not in (ENABLE_LOWER, DISABLE_LOWER): - raise InvalidArgumentValueError('Allowed values for "system-assigned" are: {}, {}.'.format(ENABLE_LOWER, DISABLE_LOWER)) + error_msg_template = 'Allowed values for "system-assigned" are: {}, {}.' + raise InvalidArgumentValueError(error_msg_template.format(ENABLE_LOWER, DISABLE_LOWER)) def validate_app_force_set_user_identity_or_warning(namespace): @@ -127,7 +137,9 @@ def validate_app_force_set_user_identity_or_warning(namespace): if len(namespace.user_assigned) == 1: single_element = namespace.user_assigned[0].strip().lower() if single_element != DISABLE_LOWER and not _is_valid_user_assigned_managed_identity_resource_id(single_element): - raise InvalidArgumentValueError('Allowed values for "user-assigned" are: {}, space-separated user-assigned managed identity resource IDs.'.format(DISABLE_LOWER)) + error_msg_template = ('Allowed values for "user-assigned" are: {}, ' + 'space-separated user-assigned managed identity resource IDs.') + raise InvalidArgumentValueError(error_msg_template.format(DISABLE_LOWER)) elif single_element == DISABLE_LOWER: namespace.user_assigned = [DISABLE_LOWER] else: diff --git a/src/spring/azext_spring/_build_service.py b/src/spring/azext_spring/_build_service.py index fce956a1fe5..0b8bd1a0bb0 100644 --- a/src/spring/azext_spring/_build_service.py +++ b/src/spring/azext_spring/_build_service.py @@ -51,24 +51,30 @@ def create_build_service(cmd, client, resource_group, service, disable_build_ser LongRunningOperation(cmd.cli_ctx)(poller) subscription = get_subscription_id(cmd.cli_ctx) - service_resource_id = '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}'.format(subscription, resource_group, service) + service_resource_id_template = '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}' + resource_id = service_resource_id_template.format(subscription, resource_group, service) build_service_properties = models.BuildServiceProperties( - container_registry='{}/containerregistries/{}'.format(service_resource_id, DEFAULT_CONTAINER_REGISTRY_NAME)) + container_registry='{}/containerregistries/{}'.format(resource_id, DEFAULT_CONTAINER_REGISTRY_NAME)) build_service_resource = models.BuildService( properties=build_service_properties) - return client.build_service.begin_create_or_update(resource_group, service, DEFAULT_BUILD_SERVICE_NAME, build_service_resource) + return client.build_service.begin_create_or_update(resource_group, service, + DEFAULT_BUILD_SERVICE_NAME, build_service_resource) else: build_service_properties = models.BuildServiceProperties( container_registry=None) build_service_resource = models.BuildService( properties=build_service_properties) - return client.build_service.begin_create_or_update(resource_group, service, DEFAULT_BUILD_SERVICE_NAME, build_service_resource) + return client.build_service.begin_create_or_update(resource_group, service, + DEFAULT_BUILD_SERVICE_NAME, build_service_resource) -def create_or_update_builder(cmd, client, resource_group, service, name, builder_json=None, builder_file=None, no_wait=False): - logger.warning('Editing builder will regenerate images for all app deployments using this builder. These new images will ' + - 'be used after app restart either manually by yourself or automatically by Azure Spring Apps in regular maintenance tasks. ' + - 'Use CLI command --"az spring build-service builder show-deployments" to view the app deployment list of the builder.') +def create_or_update_builder(cmd, client, resource_group, service, name, + builder_json=None, builder_file=None, no_wait=False): + logger.warning('Editing builder will regenerate images for all app deployments using this builder. ' + 'These new images will be used after app restart either manually by yourself or ' + 'automatically by Azure Spring Apps in regular maintenance tasks. Use CLI ' + 'command --"az spring build-service builder show-deployments" to view the app ' + 'deployment list of the builder.') builder = _update_builder(builder_file, builder_json) builder_resource = models.BuilderResource( properties=builder @@ -86,10 +92,12 @@ def builder_show_deployments(cmd, client, resource_group, service, name): def builder_delete(cmd, client, resource_group, service, name, no_wait=False): - return sdk_no_wait(no_wait, client.build_service_builder.begin_delete, resource_group, service, DEFAULT_BUILD_SERVICE_NAME, name) + return sdk_no_wait(no_wait, client.build_service_builder.begin_delete, + resource_group, service, DEFAULT_BUILD_SERVICE_NAME, name) -def create_or_update_container_registry(cmd, client, resource_group, service, name=None, server=None, username=None, password=None): +def create_or_update_container_registry(cmd, client, resource_group, service, name=None, + server=None, username=None, password=None): container_registry_properties = models.ContainerRegistryProperties( credentials=models.ContainerRegistryBasicCredentials( server=server, @@ -141,7 +149,8 @@ def build_list(cmd, client, resource_group, service): def build_delete(cmd, client, resource_group, service, name, no_wait=False): - return sdk_no_wait(no_wait, client.build_service.begin_delete_build, resource_group, service, DEFAULT_BUILD_SERVICE_NAME, name) + return sdk_no_wait(no_wait, client.build_service.begin_delete_build, + resource_group, service, DEFAULT_BUILD_SERVICE_NAME, name) def build_result_show(cmd, client, resource_group, service, build_name=None, name=None): @@ -155,11 +164,12 @@ def build_result_list(cmd, client, resource_group, service, build_name=None): def update_build_service(cmd, client, resource_group, service, registry_name=None, no_wait=False): subscription = get_subscription_id(cmd.cli_ctx) service_resource_id = '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}'.format(subscription, resource_group, service) - build_service_properties = models.BuildServiceProperties( - container_registry='{}/containerregistries/{}'.format(service_resource_id, registry_name) if registry_name else None) + registry = '{}/containerregistries/{}'.format(service_resource_id, registry_name) if registry_name else None + build_service_properties = models.BuildServiceProperties(container_registry=registry) build_service_resource = models.BuildService( properties=build_service_properties) - return sdk_no_wait(no_wait, client.build_service.begin_create_or_update, resource_group, service, DEFAULT_BUILD_SERVICE_NAME, build_service_resource) + return sdk_no_wait(no_wait, client.build_service.begin_create_or_update, + resource_group, service, DEFAULT_BUILD_SERVICE_NAME, build_service_resource) def build_service_show(cmd, client, resource_group, service): diff --git a/src/spring/azext_spring/_deployment_source_factory.py b/src/spring/azext_spring/_deployment_source_factory.py index 5f763ebf4f2..7f4f19bfbe3 100644 --- a/src/spring/azext_spring/_deployment_source_factory.py +++ b/src/spring/azext_spring/_deployment_source_factory.py @@ -147,7 +147,7 @@ def _format_container(self, container_registry=None, container_image=None, container_args = shlex.split(container_args) credential = models.ImageRegistryCredential( username=registry_username, - password=registry_password # [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="false positive")] + password=registry_password # [SuppressMessage("Microsoft.Security", "CS001:SecretInline", Justification="false positive")] # pylint: disable=line-too-long ) if registry_username or registry_password else None return models.CustomContainer( server=container_registry, diff --git a/src/spring/azext_spring/_deployment_uploadable_factory.py b/src/spring/azext_spring/_deployment_uploadable_factory.py index 88a72e1f728..b9db9d188ee 100644 --- a/src/spring/azext_spring/_deployment_uploadable_factory.py +++ b/src/spring/azext_spring/_deployment_uploadable_factory.py @@ -38,7 +38,8 @@ def upload_and_build(self, artifact_path, **_): if os.path.splitext(artifact_path)[-1] in artifact_type_list: self._upload(artifact_path) else: - raise InvalidArgumentValueError('Unexpected artifact file type, must be one of .zip, .tar.gz, .tar, .jar, .war.') + raise InvalidArgumentValueError('Unexpected artifact file type, must be one of ' + '.zip, .tar.gz, .tar, .jar, .war.') def _upload(self, artifact_path): FileService = get_sdk(self.cli_ctx, ResourceType.DATA_STORAGE, 'file#FileService') diff --git a/src/spring/azext_spring/_marketplace.py b/src/spring/azext_spring/_marketplace.py index ac79caf3392..28f9af788c9 100644 --- a/src/spring/azext_spring/_marketplace.py +++ b/src/spring/azext_spring/_marketplace.py @@ -17,7 +17,8 @@ def _spring_list_marketplace_plan(cmd, client): from .vendored_sdks.marketplace.v2018_08_01_beta import MarketplaceRPService from .vendored_sdks.marketplace.v2018_08_01_beta.models import Offer - logger.warning('To view the Azure Spring Apps Enterprise tier offering and read a detailed description, see https://aka.ms/ascmpoffer') + logger.warning('To view the Azure Spring Apps Enterprise tier offering and read a detailed description, ' + 'see https://aka.ms/ascmpoffer') client = get_mgmt_service_client(cmd.cli_ctx, MarketplaceRPService) offer = client.offer.get('{}.{}'.format(MARKETPLACE_PUBLISHER_ID, MARKETPLACE_OFFER_ID)) offer.plans = [x for x in offer.plans if _is_valid_plan(x)] diff --git a/src/spring/azext_spring/_tanzu_component.py b/src/spring/azext_spring/_tanzu_component.py index f5ac7324dcb..8f909016236 100644 --- a/src/spring/azext_spring/_tanzu_component.py +++ b/src/spring/azext_spring/_tanzu_component.py @@ -10,7 +10,9 @@ from msrestazure.tools import resource_id from .application_live_view import create as application_live_view_create from .dev_tool_portal import create_or_update as dev_tool_portal_create -from .vendored_sdks.appplatform.v2023_11_01_preview.models._app_platform_management_client_enums import ConfigurationServiceGeneration +from .vendored_sdks.appplatform.v2023_11_01_preview.models._app_platform_management_client_enums import ( + ConfigurationServiceGeneration +) from .vendored_sdks.appplatform.v2023_11_01_preview import models GATEWAY_RESOURCE_TYPE = "gateways" @@ -18,7 +20,8 @@ logger = get_logger(__name__) -def create_dev_tool_portal(cmd, client, resource_group, service, enable_application_live_view, enable_application_accelerator, **_): +def create_dev_tool_portal(cmd, client, resource_group, service, + enable_application_live_view, enable_application_accelerator, **_): if any([enable_application_live_view, enable_application_accelerator]): logger.warning('- Creating Dev Tool Portal ..') return dev_tool_portal_create(cmd, client, service, resource_group, @@ -32,7 +35,10 @@ def create_application_live_view(cmd, client, resource_group, service, enable_ap return application_live_view_create(cmd, client, service, resource_group) -def create_application_configuration_service(cmd, client, resource_group, service, enable_application_configuration_service, application_configuration_service_generation, **_): +def create_application_configuration_service(cmd, client, resource_group, service, + enable_application_configuration_service, + application_configuration_service_generation, + **_): if enable_application_configuration_service: logger.warning(" - Creating Application Configuration Service ..") acs_resource = models.ConfigurationServiceResource() @@ -63,7 +69,8 @@ def create_gateway(cmd, client, resource_group, service, enable_gateway, gateway return client.gateways.begin_create_or_update(resource_group, service, DEFAULT_NAME, gateway_resource) -def create_api_portal(cmd, client, resource_group, service, enable_api_portal, api_portal_instance_count=None, sku=None, **_): +def create_api_portal(cmd, client, resource_group, service, enable_api_portal, + api_portal_instance_count=None, sku=None, **_): if enable_api_portal: logger.warning(" - Creating API portal ..") gateway_id = resource_id( @@ -94,4 +101,5 @@ def create_application_accelerator(cmd, client, resource_group, service, enable_ properties=models.ApplicationAcceleratorProperties( ) ) - return client.application_accelerators.begin_create_or_update(resource_group, service, DEFAULT_NAME, application_accelerator_resource) + return client.application_accelerators.begin_create_or_update(resource_group, service, + DEFAULT_NAME, application_accelerator_resource) diff --git a/src/spring/azext_spring/_utils.py b/src/spring/azext_spring/_utils.py index ff26e6eb95b..c136c36e30b 100644 --- a/src/spring/azext_spring/_utils.py +++ b/src/spring/azext_spring/_utils.py @@ -21,7 +21,9 @@ from knack.util import CLIError, todict from knack.log import get_logger from azure.cli.core.azclierror import ValidationError, CLIInternalError -from .vendored_sdks.appplatform.v2023_11_01_preview.models._app_platform_management_client_enums import SupportedRuntimeValue +from .vendored_sdks.appplatform.v2023_11_01_preview.models._app_platform_management_client_enums import ( + SupportedRuntimeValue +) from ._client_factory import cf_resource_groups @@ -207,7 +209,8 @@ def get_azure_files_info(file_sas_url): def _get_azure_storage_client_info(account_type, sas_url): - regex = compile(r"http(s)?://(?P.*?)\.{0}\.(?P.*?)/(?P.*?)/(?P.*?)\?(?P.*)".format(account_type)) + pattern = r"http(s)?://(?P.*?)\.{0}\.(?P.*?)/(?P.*?)/(?P.*?)\?(?P.*)" # pylint: disable=line-too-long + regex = compile(pattern.format(account_type)) matchObj = search(regex, sas_url) account_name = matchObj.group('account_name') endpoint_suffix = matchObj.group('endpoint_suffix') @@ -330,7 +333,8 @@ def _is_resource_provider_registered(cmd, resource_provider, subscription_id=Non if not subscription_id: subscription_id = get_subscription_id(cmd.cli_ctx) try: - providers_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, subscription_id=subscription_id).providers + providers_client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, + subscription_id=subscription_id).providers registration_state = getattr(providers_client.get(resource_provider), 'registration_state', "NotRegistered") registered = (registration_state and registration_state.lower() == 'registered') @@ -343,7 +347,8 @@ def _register_resource_provider(cmd, resource_provider): from azure.mgmt.resource.resources.models import ProviderRegistrationRequest, ProviderConsentDefinition logger.warning(f"Registering resource provider {resource_provider} ...") - properties = ProviderRegistrationRequest(third_party_provider_consent=ProviderConsentDefinition(consent_to_authorization=True)) + properties = ProviderRegistrationRequest( + third_party_provider_consent=ProviderConsentDefinition(consent_to_authorization=True)) client = get_mgmt_service_client(cmd.cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES).providers try: @@ -356,7 +361,8 @@ def _register_resource_provider(cmd, resource_provider): registration = _is_resource_provider_registered(cmd, resource_provider) sleep(3) if (datetime.utcnow() - start).seconds >= timeout_secs: - raise CLIInternalError(f"Timed out while waiting for the {resource_provider} resource provider to be registered.") + raise CLIInternalError(f"Timed out while waiting for the {resource_provider} " + f"resource provider to be registered.") except Exception as e: msg = ("This operation requires registering the resource provider {0}. " diff --git a/src/spring/azext_spring/_validators.py b/src/spring/azext_spring/_validators.py index 933114e1720..f3634a2d4f5 100644 --- a/src/spring/azext_spring/_validators.py +++ b/src/spring/azext_spring/_validators.py @@ -93,7 +93,8 @@ def _validate_terms(cmd, namespace): def _check_tanzu_components_not_enable(cmd, namespace): - suffix = 'can only be used for Azure Spring Apps Enterprise. Please add --sku="Enterprise" to create Enterprise instance.' + suffix = ('can only be used for Azure Spring Apps Enterprise. ' + 'Please add --sku="Enterprise" to create Enterprise instance.') if namespace.enable_application_configuration_service: raise ArgumentUsageError('--enable-application-configuration-service {}'.format(suffix)) if namespace.enable_service_registry: @@ -264,7 +265,8 @@ def validate_tracing_parameters_asc_create(namespace): def validate_dataplane_public_endpoint(namespace): - if namespace.enable_log_stream_public_endpoint is not None and namespace.enable_dataplane_public_endpoint is not None: + if (namespace.enable_log_stream_public_endpoint is not None + and namespace.enable_dataplane_public_endpoint is not None): if namespace.enable_log_stream_public_endpoint != namespace.enable_dataplane_public_endpoint: raise InvalidArgumentValueError("The value of enable_log_stream_public_endpoint and " "enable_dataplane_public_endpoint should be the same, " @@ -321,8 +323,9 @@ def _validate_app_insights_parameters(namespace): def validate_app_insights_command_not_supported_tier(cmd, namespace): if is_enterprise_tier(cmd, namespace.resource_group, namespace.name): - raise NotSupportedPricingTierError("Enterprise tier service instance {} in group {} is not supported in this command, ".format(namespace.name, namespace.resource_group) + - "please refer to 'az spring build-service builder buildpack-binding' command group.") + error_msg_template = ("Enterprise tier service instance {} in group {} is not supported in this command, " + "please refer to 'az spring build-service builder buildpack-binding' command group.") + raise NotSupportedPricingTierError(error_msg_template.format(namespace.name, namespace.resource_group)) def validate_vnet(cmd, namespace): @@ -355,7 +358,8 @@ def validate_vnet(cmd, namespace): app_vnet_id = _parse_vnet_id_from_subnet(namespace.app_subnet) service_runtime_vnet_id = _parse_vnet_id_from_subnet(namespace.service_runtime_subnet) if app_vnet_id.lower() != service_runtime_vnet_id.lower(): - raise InvalidArgumentValueError('--app-subnet and --service-runtime-subnet should be in the same Virtual Networks.') + raise InvalidArgumentValueError('--app-subnet and --service-runtime-subnet should be ' + 'in the same Virtual Networks.') vnet_id = app_vnet_id if namespace.app_subnet.lower() == namespace.service_runtime_subnet.lower(): raise InvalidArgumentValueError('--app-subnet and --service-runtime-subnet should not be the same.') @@ -397,7 +401,8 @@ def _validate_subnet(namespace, subnet): raise InvalidArgumentValueError('--{} should not have connected device.'.format(name)) address = ip_network(subnet["addressPrefix"], strict=False) if address.prefixlen > limit: - raise InvalidArgumentValueError('--{0} should contain at least /{1} address, got /{2}'.format(name, limit, address.prefixlen)) + error_msg_template = '--{0} should contain at least /{1} address, got /{2}' + raise InvalidArgumentValueError(error_msg_template.format(name, limit, address.prefixlen)) def _get_vnet(cmd, vnet_id): @@ -581,7 +586,8 @@ def _validate_resource_group_name(name, message_name): return matchObj = match(r'^[-\w\._\(\)]+$', name) if matchObj is None: - raise InvalidArgumentValueError('--{0} must conform to the following pattern: \'^[-\\w\\._\\(\\)]+$\'.'.format(message_name)) + error_msg_template = '--{0} must conform to the following pattern: \'^[-\\w\\._\\(\\)]+$\'.' + raise InvalidArgumentValueError(error_msg_template.format(message_name)) def _validate_route_table(namespace, vnet_obj): @@ -595,7 +601,8 @@ def _validate_route_table(namespace, vnet_obj): if app_route_table_id and runtime_route_table_id: if app_route_table_id == runtime_route_table_id: - raise InvalidArgumentValueError('--service-runtime-subnet and --app-subnet should associate with different route tables.') + raise InvalidArgumentValueError('--service-runtime-subnet and --app-subnet should ' + 'associate with different route tables.') if (app_route_table_id and not runtime_route_table_id) \ or (not app_route_table_id and runtime_route_table_id): raise InvalidArgumentValueError( @@ -651,9 +658,9 @@ def validate_jar(namespace): if values["spring_cloud_version"] < "2.2.5": if not values["ms_sdk_version"] or values["ms_sdk_version"] > "2.2.1": telemetry.set_user_fault("old_spring_cloud_version") - raise InvalidArgumentValueError( - "The spring cloud {} you are using is not supported. To get the latest supported " - "versions please refer to: https://aka.ms/ascspringversion".format(values["spring_cloud_version"]) + tips) + error_msg_template = ('The spring cloud {} you are using is not supported. To get the latest ' + 'supported versions please refer to: https://aka.ms/ascspringversion') + raise InvalidArgumentValueError(error_msg_template.format(values["spring_cloud_version"]) + tips) else: if values["ms_sdk_version"] and values["ms_sdk_version"] <= "2.2.1": telemetry.set_user_fault("old_ms_sdk_version") @@ -744,17 +751,21 @@ def validate_config_server_ssh_or_warn(namespace): strict_host_key_checking = namespace.strict_host_key_checking if private_key or host_key or host_key_algorithm or strict_host_key_checking: logger.warning("SSH authentication only supports SHA-1 signature under Config Server restriction. " - "Please refer to https://aka.ms/asa-configserver-ssh to understand how to use SSH under this restriction.") + "Please refer to https://aka.ms/asa-configserver-ssh to understand how to use " + "SSH under this restriction.") def validate_managed_environment(namespace): managed_environment_id = namespace.managed_environment if managed_environment_id: if not is_valid_resource_id(managed_environment_id): - raise InvalidArgumentValueError('--managed-environment {0} is not a valid Container App Environment resource ID'.format(managed_environment_id)) + error_msg_template = '--managed-environment {0} is not a valid Container App Environment resource ID' + raise InvalidArgumentValueError(error_msg_template.format(managed_environment_id)) managed_environment = parse_resource_id(managed_environment_id) - if managed_environment['namespace'].lower() != 'microsoft.app' or managed_environment['type'].lower() != 'managedenvironments': - raise InvalidArgumentValueError('--managed-environment {0} is not a valid Container App Environment resource ID'.format(managed_environment_id)) + if (managed_environment['namespace'].lower() != 'microsoft.app' + or managed_environment['type'].lower() != 'managedenvironments'): + raise InvalidArgumentValueError('--managed-environment {0} is not a valid Container App ' + 'Environment resource ID'.format(managed_environment_id)) def validate_server_version(cmd, namespace): @@ -765,10 +776,12 @@ def validate_server_version(cmd, namespace): def validate_planned_maintenance(namespace): if namespace.enable_planned_maintenance is True \ and (namespace.planned_maintenance_day is None or namespace.planned_maintenance_start_hour is None): - raise InvalidArgumentValueError("Invalid value: --planned-maintenance-day and --planned-maintenance-start-hour must be set when --enable-planned-maintenance is set.") + raise InvalidArgumentValueError("Invalid value: --planned-maintenance-day and --planned-maintenance-start-hour " + "must be set when --enable-planned-maintenance is set.") if namespace.enable_planned_maintenance is False \ and (namespace.planned_maintenance_day is not None or namespace.planned_maintenance_start_hour is not None): - raise InvalidArgumentValueError("Invalid value: --planned-maintenance-day and --planned-maintenance-start-hour can only be set when --enable-planned-maintenance is set.") + raise InvalidArgumentValueError("Invalid value: --planned-maintenance-day and --planned-maintenance-start-hour " + "can only be set when --enable-planned-maintenance is set.") if namespace.planned_maintenance_start_hour is not None \ and (namespace.planned_maintenance_start_hour < 0 or namespace.planned_maintenance_start_hour > 23): raise InvalidArgumentValueError("Invalid value: planned maintenance start hour must be in the range [0,23].") diff --git a/src/spring/azext_spring/api_portal.py b/src/spring/azext_spring/api_portal.py index 8afea062d3b..e5f62841030 100644 --- a/src/spring/azext_spring/api_portal.py +++ b/src/spring/azext_spring/api_portal.py @@ -68,7 +68,8 @@ def api_portal_update(cmd, client, resource_group, service, issuer_uri=issuer_uri, ) - target_api_try_out_state = _get_api_try_out_state(enable_api_try_out, api_portal.properties.api_try_out_enabled_state) + target_api_try_out_state = _get_api_try_out_state(enable_api_try_out, + api_portal.properties.api_try_out_enabled_state) properties = models.ApiPortalProperties( public=assign_endpoint if assign_endpoint is not None else api_portal.properties.public, diff --git a/src/spring/azext_spring/app_managed_identity.py b/src/spring/azext_spring/app_managed_identity.py index 3c228e11ffb..d00af75c92e 100644 --- a/src/spring/azext_spring/app_managed_identity.py +++ b/src/spring/azext_spring/app_managed_identity.py @@ -79,7 +79,8 @@ def app_identity_remove(cmd, """ app = client.apps.get(resource_group, service, name) if _app_not_updatable(app): - raise ConflictRequestError("Failed to remove managed identities since app is in {} state.".format(app.properties.provisioning_state)) + error_msg_template = "Failed to remove managed identities since app is in {} state." + raise ConflictRequestError(error_msg_template.format(app.properties.provisioning_state)) if not app.identity: logger.warning("Skip remove managed identity since no identities assigned to app.") @@ -287,7 +288,8 @@ def _create_role_assignment(cmd, client, resource_group, service, name, role, sc def _get_new_user_identities_for_remove(exist_user_identity_dict, user_identity_list_to_remove): """ :param exist_user_identity_dict: A dict from user-assigned managed identity resource id to identity objecct. - :param user_identity_list_to_remove: None, an empty list or a list of string of user-assigned managed identity resource id to remove. + :param user_identity_list_to_remove: None, an empty list or a list of string of user-assigned managed + identity resource id to remove. :return A list of string of user-assigned managed identity resource ID. """ if not exist_user_identity_dict: @@ -345,7 +347,8 @@ def _get_new_identity_type_for_remove(exist_identity_type, is_remove_system_iden def _get_user_identity_payload_for_remove(new_identity_type, user_identity_list_to_remove): """ :param new_identity_type: ManagedIdentityType - :param user_identity_list_to_remove: None, an empty list or a list of string of user-assigned managed identity resource id to remove. + :param user_identity_list_to_remove: None, an empty list or a list of string of user-assigned managed + identity resource id to remove. :return None object or a non-empty dict from user-assigned managed identity resource id to None object """ user_identity_payload = {} diff --git a/src/spring/azext_spring/application_accelerator.py b/src/spring/azext_spring/application_accelerator.py index dac31a59930..c958560c315 100644 --- a/src/spring/azext_spring/application_accelerator.py +++ b/src/spring/azext_spring/application_accelerator.py @@ -12,7 +12,9 @@ create_or_update as create_or_update_dev_tool_portal, _get_desired_state as get_dev_tool_portal_desired_state) from ._utils import (wait_till_end) -from .vendored_sdks.appplatform.v2023_11_01_preview.models._app_platform_management_client_enums import (CustomizedAcceleratorType) +from .vendored_sdks.appplatform.v2023_11_01_preview.models._app_platform_management_client_enums import ( + CustomizedAcceleratorType +) DEFAULT_NAME = "default" logger = get_logger(__name__) @@ -26,7 +28,10 @@ def application_accelerator_create(cmd, client, resource_group, service, no_wait properties = models.ApplicationAcceleratorProperties( ) application_accelerator_resource = models.ApplicationAcceleratorResource(properties=properties) - poller = client.application_accelerators.begin_create_or_update(resource_group, service, DEFAULT_NAME, application_accelerator_resource) + poller = client.application_accelerators.begin_create_or_update(resource_group, + service, + DEFAULT_NAME, + application_accelerator_resource) dev_tool_portal_poller = _get_enable_dev_tool_portal_poller(cmd, client, service, resource_group) pollers = [x for x in [poller, dev_tool_portal_poller] if x is not None] if not no_wait: @@ -84,7 +89,8 @@ def customized_accelerator_show(cmd, client, resource_group, service, name): def customized_accelerator_sync_cert(cmd, client, resource_group, service, name, no_wait=False): customized_accelerator_resource = client.customized_accelerators.get(resource_group, service, DEFAULT_NAME, name) - return sdk_no_wait(no_wait, client.customized_accelerators.begin_create_or_update, resource_group, service, DEFAULT_NAME, name, customized_accelerator_resource) + return sdk_no_wait(no_wait, client.customized_accelerators.begin_create_or_update, + resource_group, service, DEFAULT_NAME, name, customized_accelerator_resource) def customized_accelerator_upsert(cmd, client, resource_group, service, name, @@ -114,7 +120,8 @@ def customized_accelerator_upsert(cmd, client, resource_group, service, name, caCertResourceId = None if ca_cert_name: subscription = get_subscription_id(cmd.cli_ctx) - caCertResourceId = "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/certificates/{}".format(subscription, resource_group, service, ca_cert_name) + resource_id = "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/certificates/{}" + caCertResourceId = resource_id.format(subscription, resource_group, service, ca_cert_name) if username and password: auth_setting = models.AcceleratorBasicAuthSetting( @@ -150,11 +157,13 @@ def customized_accelerator_upsert(cmd, client, resource_group, service, name, git_repository=git_repository ) customized_accelerator_resource = models.CustomizedAcceleratorResource(properties=properties) - return sdk_no_wait(no_wait, client.customized_accelerators.begin_create_or_update, resource_group, service, DEFAULT_NAME, name, customized_accelerator_resource) + return sdk_no_wait(no_wait, client.customized_accelerators.begin_create_or_update, + resource_group, service, DEFAULT_NAME, name, customized_accelerator_resource) def customized_accelerator_delete(cmd, client, resource_group, service, name, no_wait=False): - return sdk_no_wait(no_wait, client.customized_accelerators.begin_delete, resource_group, service, DEFAULT_NAME, name) + return sdk_no_wait(no_wait, client.customized_accelerators.begin_delete, + resource_group, service, DEFAULT_NAME, name) def predefined_accelerator_list(cmd, client, resource_group, service): @@ -166,8 +175,10 @@ def predefined_accelerator_show(cmd, client, resource_group, service, name): def predefined_accelerator_disable(cmd, client, resource_group, service, name, no_wait=False): - return sdk_no_wait(no_wait, client.predefined_accelerators.begin_disable, resource_group, service, DEFAULT_NAME, name) + return sdk_no_wait(no_wait, client.predefined_accelerators.begin_disable, + resource_group, service, DEFAULT_NAME, name) def predefined_accelerator_enable(cmd, client, resource_group, service, name, no_wait=False): - return sdk_no_wait(no_wait, client.predefined_accelerators.begin_enable, resource_group, service, DEFAULT_NAME, name) + return sdk_no_wait(no_wait, client.predefined_accelerators.begin_enable, + resource_group, service, DEFAULT_NAME, name) diff --git a/src/spring/azext_spring/buildpack_binding.py b/src/spring/azext_spring/buildpack_binding.py index 3ec51fec812..a85cad67d1b 100644 --- a/src/spring/azext_spring/buildpack_binding.py +++ b/src/spring/azext_spring/buildpack_binding.py @@ -4,6 +4,8 @@ # -------------------------------------------------------------------------------------------- # pylint: disable=wrong-import-order +# pylint: disable=line-too-long + from .vendored_sdks.appplatform.v2023_11_01_preview import models from azure.cli.core.util import sdk_no_wait from ._utils import get_portal_uri diff --git a/src/spring/azext_spring/custom.py b/src/spring/azext_spring/custom.py index 44e5b8b92bd..7babbb4555c 100644 --- a/src/spring/azext_spring/custom.py +++ b/src/spring/azext_spring/custom.py @@ -23,7 +23,9 @@ from knack.util import CLIError from .vendored_sdks.appplatform.v2023_11_01_preview import models, AppPlatformManagementClient from knack.log import get_logger -from azure.cli.core.azclierror import ClientRequestError, FileOperationError, InvalidArgumentValueError, ResourceNotFoundError +from azure.cli.core.azclierror import ( + ClientRequestError, FileOperationError, InvalidArgumentValueError, ResourceNotFoundError +) from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id from azure.cli.core.util import sdk_no_wait from azure.mgmt.applicationinsights import ApplicationInsightsManagementClient diff --git a/src/spring/azext_spring/gateway.py b/src/spring/azext_spring/gateway.py index 354ac456676..94095bf4fc7 100644 --- a/src/spring/azext_spring/gateway.py +++ b/src/spring/azext_spring/gateway.py @@ -84,13 +84,16 @@ def gateway_update(cmd, client, resource_group, service, ) api_metadata_properties = _update_api_metadata( - gateway.properties.api_metadata_properties, api_title, api_description, api_doc_location, api_version, server_url) + gateway.properties.api_metadata_properties, api_title, + api_description, api_doc_location, api_version, server_url) cors_properties = _update_cors( - gateway.properties.cors_properties, allowed_origins, allowed_origin_patterns, allowed_methods, allowed_headers, max_age, allow_credentials, exposed_headers) + gateway.properties.cors_properties, allowed_origins, allowed_origin_patterns, + allowed_methods, allowed_headers, max_age, allow_credentials, exposed_headers) client_auth = _update_client_auth(client, resource_group, service, - gateway.properties.client_auth, enable_certificate_verification, certificate_names) + gateway.properties.client_auth, + enable_certificate_verification, certificate_names) resource_requests = models.GatewayResourceRequests( cpu=cpu or gateway.properties.resource_requests.cpu, @@ -223,7 +226,8 @@ def gateway_route_config_remove(cmd, client, resource_group, service, name): def _update_api_metadata(existing, api_title, api_description, api_documentation_location, version, server_url): - if api_title is None and api_description is None and api_documentation_location is None and version is None and server_url is None: + if (api_title is None and api_description is None + and api_documentation_location is None and version is None and server_url is None): return existing api_metadata = models.GatewayApiMetadataProperties() if existing is None else existing if api_title is not None: @@ -239,8 +243,11 @@ def _update_api_metadata(existing, api_title, api_description, api_documentation return api_metadata -def _update_cors(existing, allowed_origins, allowed_origin_patterns, allowed_methods, allowed_headers, max_age, allow_credentials, exposed_headers): - if allowed_origins is None and allowed_origin_patterns is None and allowed_methods is None and allowed_headers is None and max_age is None and allow_credentials is None and exposed_headers is None: +def _update_cors(existing, allowed_origins, allowed_origin_patterns, allowed_methods, + allowed_headers, max_age, allow_credentials, exposed_headers): + if (allowed_origins is None and allowed_origin_patterns is None + and allowed_methods is None and allowed_headers is None + and max_age is None and allow_credentials is None and exposed_headers is None): return existing cors = existing if existing is not None else models.GatewayCorsProperties() if allowed_origins is not None: @@ -276,7 +283,7 @@ def _update_client_auth(client, resource_group, service, existing, enable_certif return existing client_auth = existing if existing is not None else models.GatewayPropertiesClientAuth() if enable_certificate_verification is not None: - client_auth.certificate_verification = models.GatewayCertificateVerification.ENABLED if enable_certificate_verification else models.GatewayCertificateVerification.DISABLED + client_auth.certificate_verification = models.GatewayCertificateVerification.ENABLED if enable_certificate_verification else models.GatewayCertificateVerification.DISABLED # pylint: disable=line-too-long if certificate_names is not None: client_auth.certificates = [] if certificate_names == "": @@ -337,7 +344,8 @@ def _create_or_update_gateway_route_configs(client, resource_group, service, nam route_properties.app_resource_id = app_resource_id route_config_resource = models.GatewayRouteConfigResource( properties=route_properties) - return client.gateway_route_configs.begin_create_or_update(resource_group, service, DEFAULT_NAME, name, route_config_resource) + return client.gateway_route_configs.begin_create_or_update(resource_group, service, + DEFAULT_NAME, name, route_config_resource) def _get_app_resource_id_by_name(client, resource_group, service, app_name): diff --git a/src/spring/azext_spring/spring_instance.py b/src/spring/azext_spring/spring_instance.py index 3682e42cf9d..985a72ab9cf 100644 --- a/src/spring/azext_spring/spring_instance.py +++ b/src/spring/azext_spring/spring_instance.py @@ -131,8 +131,10 @@ def before_create(self, **_): def after_create(self, no_wait=None, **kwargs): # should create build service before creating build agent pool and app insights if not no_wait and not kwargs['disable_build_service']: - poller = create_build_service(self.cmd, self.client, self.resource_group, self.name, kwargs['disable_build_service'], - kwargs['registry_server'], kwargs['registry_username'], kwargs['registry_password']) + poller = create_build_service(self.cmd, self.client, self.resource_group, + self.name, kwargs['disable_build_service'], + kwargs['registry_server'], kwargs['registry_username'], + kwargs['registry_password']) LongRunningOperation(self.cmd.cli_ctx)(poller) pollers = [ # create sub components like Service registry, ACS, build service, etc. From f234657a59d22a07945440caa3e8e28128d3ee5f Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Mon, 18 Dec 2023 15:01:34 +0800 Subject: [PATCH 17/19] Fix style errors - C0301 --- src/spring/azext_spring/_build_service.py | 3 +- .../azext_spring/_buildservices_factory.py | 23 ++++-- .../azext_spring/_deployment_factory.py | 11 +-- .../_deployment_source_factory.py | 14 ++-- src/spring/azext_spring/_resource_quantity.py | 3 +- .../azext_spring/_validators_enterprise.py | 70 +++++++++++++------ .../application_configuration_service.py | 2 +- src/spring/azext_spring/buildpack_binding.py | 3 +- 8 files changed, 85 insertions(+), 44 deletions(-) diff --git a/src/spring/azext_spring/_build_service.py b/src/spring/azext_spring/_build_service.py index 0b8bd1a0bb0..5229b2843a4 100644 --- a/src/spring/azext_spring/_build_service.py +++ b/src/spring/azext_spring/_build_service.py @@ -163,7 +163,8 @@ def build_result_list(cmd, client, resource_group, service, build_name=None): def update_build_service(cmd, client, resource_group, service, registry_name=None, no_wait=False): subscription = get_subscription_id(cmd.cli_ctx) - service_resource_id = '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}'.format(subscription, resource_group, service) + service_resource_id_template = '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}' + service_resource_id = service_resource_id_template.format(subscription, resource_group, service) registry = '{}/containerregistries/{}'.format(service_resource_id, registry_name) if registry_name else None build_service_properties = models.BuildServiceProperties(container_registry=registry) build_service_resource = models.BuildService( diff --git a/src/spring/azext_spring/_buildservices_factory.py b/src/spring/azext_spring/_buildservices_factory.py index 1a4275d347a..62aa0837fcc 100644 --- a/src/spring/azext_spring/_buildservices_factory.py +++ b/src/spring/azext_spring/_buildservices_factory.py @@ -38,14 +38,17 @@ def build_and_get_result(self, total_steps, **kwargs): logger.warning("[1/{}] Requesting for upload URL.".format(total_steps)) upload_info = self._get_upload_info() logger.warning("[2/{}] Uploading package to blob.".format(total_steps)) - uploader_selector(cli_ctx=self.cmd.cli_ctx, upload_url=upload_info.upload_url, **kwargs).upload_and_build(**kwargs) + uploader_selector(cli_ctx=self.cmd.cli_ctx, + upload_url=upload_info.upload_url, + **kwargs).upload_and_build(**kwargs) if 'app' in kwargs: build_name = kwargs['app'] else: build_name = kwargs['build_name'] logger.warning("[3/{}] Creating or Updating build '{}'.".format(total_steps, build_name)) build_result_id = self._queue_build(upload_info.relative_path, **kwargs) - logger.warning("[4/{}] Waiting for building container image to finish. This may take a few minutes.".format(total_steps)) + logger.warning("[4/{}] Waiting for building container image to finish. " + "This may take a few minutes.".format(total_steps)) self._wait_build_finished(build_result_id) return build_result_id @@ -60,10 +63,12 @@ def _get_upload_info(self): except AttributeError as e: raise AzureInternalError("Failed to get a SAS URL to upload context. Error: {}".format(e)) - def _queue_build(self, relative_path=None, builder=None, build_env=None, build_cpu=None, build_memory=None, app=None, deployment=None, build_name=None, + def _queue_build(self, relative_path=None, builder=None, build_env=None, build_cpu=None, + build_memory=None, app=None, deployment=None, build_name=None, apms=None, certificates=None, build_certificates=None, **_): subscription = get_subscription_id(self.cmd.cli_ctx) - service_resource_id = '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}'.format(subscription, self.resource_group, self.service) + service_resource_id_template = '/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}' + service_resource_id = service_resource_id_template.format(subscription, self.resource_group, self.service) build_resource_requests = models.BuildResourceRequests( cpu=build_cpu, memory=build_memory) @@ -114,7 +119,9 @@ def _wait_build_finished(self, build_result_id): log_url = self._try_get_build_log_url(build_result_id) if hasattr(result.properties, "error") and result.properties.error: build_error = result.properties.error - error_msg = "Failed to build container image, error code: {}, message: {}, check the build logs {} for more details and retry.".format(build_error.code, build_error.message, log_url) + error_msg_template = ("Failed to build container image, error code: {}, message: {}, " + "check the build logs {} for more details and retry.") + error_msg = error_msg_template.format(build_error.code, build_error.message, log_url) else: error_msg = "Failed to build container image, please check the build logs {} and retry.".format(log_url) raise DeploymentError(error_msg) @@ -126,7 +133,8 @@ def _get_build_result(self, id): build_service = resource_id['child_name_1'] build = resource_id['child_name_2'] build_result_name = resource_id['resource_name'] - response = self.client.build_service.get_build_result(resource_group, service, build_service, build, build_result_name) + response = self.client.build_service.get_build_result(resource_group, service, + build_service, build, build_result_name) self.progress_bar.add(message=response.properties.provisioning_state) return response @@ -173,7 +181,8 @@ def _start_build_stage_log(self, result, pod, stage_name): # refresh the build result result = self._get_build_result(result.id) if result.properties.provisioning_state in self.terminated_state: - logger.info('The build result is already terminated, cannot stream the log out for stage {}.'.format(stage_name)) + logger.info('The build result is already terminated, ' + 'cannot stream the log out for stage {}.'.format(stage_name)) return stage = next(iter(x for x in result.properties.build_stages if x.name == stage_name), None) if not stage: diff --git a/src/spring/azext_spring/_deployment_factory.py b/src/spring/azext_spring/_deployment_factory.py index f9c9a460f03..02623b976cb 100644 --- a/src/spring/azext_spring/_deployment_factory.py +++ b/src/spring/azext_spring/_deployment_factory.py @@ -179,14 +179,15 @@ def _load_probe_config(self, probe_config=None, **_): ) else: raise InvalidArgumentValueError("ProbeAction.Type is invalid") + probe = data['probe'] probe_settings = models.Probe( probe_action=probe_action, disable_probe=False, - initial_delay_seconds=data['probe']['initialDelaySeconds'] if 'initialDelaySeconds' in data['probe'] else None, - period_seconds=data['probe']['periodSeconds'] if 'periodSeconds' in data['probe'] else None, - timeout_seconds=data['probe']['timeoutSeconds'] if 'timeoutSeconds' in data['probe'] else None, - failure_threshold=data['probe']['failureThreshold'] if 'failureThreshold' in data['probe'] else None, - success_threshold=data['probe']['successThreshold'] if 'successThreshold' in data['probe'] else None + initial_delay_seconds=probe['initialDelaySeconds'] if 'initialDelaySeconds' in probe else None, + period_seconds=probe['periodSeconds'] if 'periodSeconds' in probe else None, + timeout_seconds=probe['timeoutSeconds'] if 'timeoutSeconds' in probe else None, + failure_threshold=probe['failureThreshold'] if 'failureThreshold' in probe else None, + success_threshold=probe['successThreshold'] if 'successThreshold' in probe else None ) return probe_settings diff --git a/src/spring/azext_spring/_deployment_source_factory.py b/src/spring/azext_spring/_deployment_source_factory.py index 7f4f19bfbe3..ac8f70daa04 100644 --- a/src/spring/azext_spring/_deployment_source_factory.py +++ b/src/spring/azext_spring/_deployment_source_factory.py @@ -24,7 +24,8 @@ def validate_source(self, **kwargs): invalid_input = {k: v for k, v in kwargs.items() if k in ['main_entry', 'target_module'] and v is not None} if any(invalid_input): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) - runtime_version = kwargs.get('runtime_version') or kwargs.get('deployment_resource').properties.source.runtime_version + runtime_version = (kwargs.get('runtime_version') + or kwargs.get('deployment_resource').properties.source.runtime_version) raise ArgumentUsageError('{} cannot be set when --runtime-version is {}.' .format(invalid_input_str, runtime_version)) @@ -56,11 +57,13 @@ def validate_source(self, **kwargs): invalid_input = {k: v for k, v in kwargs.items() if k in ['main_entry', 'target_module'] and v is not None} if any(invalid_input): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) - runtime_version = kwargs.get('runtime_version') or kwargs.get('deployment_resource').properties.source.runtime_version + runtime_version = (kwargs.get('runtime_version') + or kwargs.get('deployment_resource').properties.source.runtime_version) raise ArgumentUsageError('{} cannot be set when --runtime-version is {}.' .format(invalid_input_str, runtime_version)) - def format_source(self, deployable_path=None, runtime_version=None, server_version=None, version=None, jvm_options=None, **_): + def format_source(self, deployable_path=None, runtime_version=None, + server_version=None, version=None, jvm_options=None, **_): if all(x is None for x in [deployable_path, runtime_version, server_version, version, jvm_options]): return return models.WarUploadedUserSourceInfo( @@ -90,7 +93,8 @@ def validate_source(self, **kwargs): invalid_input = {k: v for k, v in kwargs.items() if k in ['jvm_options'] and v is not None} if any(invalid_input): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) - runtime_version = kwargs.get('runtime_version') or kwargs.get('deployment_resource').properties.source.runtime_version + runtime_version = (kwargs.get('runtime_version') + or kwargs.get('deployment_resource').properties.source.runtime_version) raise ArgumentUsageError('{} cannot be set when --runtime-version is {}.' .format(invalid_input_str, runtime_version)) @@ -119,7 +123,7 @@ def fulfilled_options_from_original_source_info(self, deployment_resource, class CustomContainerSource(BaseSource): def validate_source(self, **kwargs): - invalid_input = {k: v for k, v in kwargs.items() if k in ['jvm_options', 'main_entry', 'target_module'] and v is not None} + invalid_input = {k: v for k, v in kwargs.items() if k in ['jvm_options', 'main_entry', 'target_module'] and v is not None} # pylint: disable=line-too-long if any(invalid_input): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) raise ArgumentUsageError('{} cannot be set when --container-image is set.' diff --git a/src/spring/azext_spring/_resource_quantity.py b/src/spring/azext_spring/_resource_quantity.py index a181730d86c..8b21d959ce1 100644 --- a/src/spring/azext_spring/_resource_quantity.py +++ b/src/spring/azext_spring/_resource_quantity.py @@ -22,7 +22,8 @@ def validate_cpu(cpu): # some digit(s) followed by an optional m if not re.match(r"^\d+m?$", cpu): - raise InvalidArgumentValueError("CPU quantity should be millis (250m, 500m, 750m, 1250m) or integer (1, 2, ...)") + raise InvalidArgumentValueError("CPU quantity should be millis (250m, 500m, 750m, 1250m) " + "or integer (1, 2, ...)") return cpu diff --git a/src/spring/azext_spring/_validators_enterprise.py b/src/spring/azext_spring/_validators_enterprise.py index 14ac40e8833..387fe58fc87 100644 --- a/src/spring/azext_spring/_validators_enterprise.py +++ b/src/spring/azext_spring/_validators_enterprise.py @@ -16,7 +16,9 @@ from azure.cli.core.commands.client_factory import get_subscription_id from knack.log import get_logger from .vendored_sdks.appplatform.v2023_11_01_preview.models import (ApmReference, CertificateReference) -from .vendored_sdks.appplatform.v2023_11_01_preview.models._app_platform_management_client_enums import (ApmType, ConfigurationServiceGeneration) +from .vendored_sdks.appplatform.v2023_11_01_preview.models._app_platform_management_client_enums import ( + ApmType, ConfigurationServiceGeneration +) from ._gateway_constant import (GATEWAY_RESPONSE_CACHE_SCOPE_ROUTE, GATEWAY_RESPONSE_CACHE_SCOPE_INSTANCE, GATEWAY_RESPONSE_CACHE_SIZE_RESET_VALUE, GATEWAY_RESPONSE_CACHE_TTL_RESET_VALUE) @@ -33,17 +35,20 @@ def only_support_enterprise(cmd, namespace): - if namespace.resource_group and namespace.service and not is_enterprise_tier(cmd, namespace.resource_group, namespace.service): + if (namespace.resource_group and namespace.service + and not is_enterprise_tier(cmd, namespace.resource_group, namespace.service)): raise ClientRequestError("'{}' only supports for Enterprise tier Spring instance.".format(namespace.command)) def not_support_enterprise(cmd, namespace): - if namespace.resource_group and namespace.service and is_enterprise_tier(cmd, namespace.resource_group, namespace.service): + if (namespace.resource_group and namespace.service + and is_enterprise_tier(cmd, namespace.resource_group, namespace.service)): raise ClientRequestError("'{}' doesn't support for Enterprise tier Spring instance.".format(namespace.command)) def validate_build_env(cmd, namespace): - if namespace.build_env is not None and namespace.resource_group and namespace.service and not is_enterprise_tier(cmd, namespace.resource_group, namespace.service): + if (namespace.build_env is not None and namespace.resource_group and namespace.service + and not is_enterprise_tier(cmd, namespace.resource_group, namespace.service)): raise ArgumentUsageError("'--build-env' only supports for Enterprise tier Spring instance.") else: if isinstance(namespace.build_env, list): @@ -59,17 +64,22 @@ def validate_build_env(cmd, namespace): result = {comps[0]: comps[1]} env_dict.update(result) else: - raise ArgumentUsageError("The env name {} is not allowed. The valid env name should follow the pattern '[-._a-zA-Z][-._a-zA-Z0-9]*'(For example, BP_JVM_VERSION).".format(comps[0])) + error_msg_template = ("The env name {} is not allowed. The valid env name should " + "follow the pattern '[-._a-zA-Z][-._a-zA-Z0-9]*'" + "(For example, BP_JVM_VERSION).") + raise ArgumentUsageError(error_msg_template.format(comps[0])) namespace.build_env = env_dict def validate_target_module(cmd, namespace): - if namespace.target_module is not None and namespace.resource_group and namespace.service and is_enterprise_tier(cmd, namespace.resource_group, namespace.service): + if (namespace.target_module is not None and namespace.resource_group and namespace.service + and is_enterprise_tier(cmd, namespace.resource_group, namespace.service)): raise ArgumentUsageError("'--target-module' doesn't support for Enterprise tier Spring instance.") def validate_runtime_version(cmd, namespace): - if namespace.runtime_version is not None and namespace.resource_group and namespace.service and is_enterprise_tier(cmd, namespace.resource_group, namespace.service): + if (namespace.runtime_version is not None and namespace.resource_group and namespace.service + and is_enterprise_tier(cmd, namespace.resource_group, namespace.service)): raise ArgumentUsageError("'--runtime-version' doesn't support for Enterprise tier Spring instance.") @@ -109,7 +119,8 @@ def validate_build_pool_size(namespace): if namespace.build_pool_size is None and not namespace.disable_build_service: namespace.build_pool_size = 'S1' elif namespace.build_pool_size is not None and namespace.disable_build_service: - raise InvalidArgumentValueError("Conflict detected: '--build-pool-size' can not be set with '--disable-build-service'.") + raise InvalidArgumentValueError("Conflict detected: '--build-pool-size' can " + "not be set with '--disable-build-service'.") else: if namespace.build_pool_size is not None: raise ClientRequestError("You can only specify --build-pool-size with enterprise tier.") @@ -118,7 +129,9 @@ def validate_build_pool_size(namespace): def validate_build_service(namespace): if _parse_sku_name(namespace.sku) == 'enterprise': if (namespace.registry_server or namespace.registry_username or namespace.registry_password is not None) \ - and ((namespace.registry_server is None) or (namespace.registry_username is None) or (namespace.registry_password is None)): + and ((namespace.registry_server is None) + or (namespace.registry_username is None) + or (namespace.registry_password is None)): raise InvalidArgumentValueError( "The'--registry-server', '--registry-username' and '--registry-password' should be specified together.") if (namespace.registry_server or namespace.registry_username or namespace.registry_password is not None) \ @@ -127,7 +140,8 @@ def validate_build_service(namespace): "Conflict detected: '--registry-server', '--registry-username' and '--registry-password' " "can not be set with '--disable-build-service'.") else: - if namespace.disable_build_service or namespace.registry_server or namespace.registry_username or namespace.registry_password is not None: + if (namespace.disable_build_service or namespace.registry_server + or namespace.registry_username or namespace.registry_password is not None): raise InvalidArgumentValueError("The build service is only supported with enterprise tier.") @@ -195,7 +209,8 @@ def validate_artifact_path(namespace): if values is None: # ignore jar_file check return - file_size, spring_boot_version, spring_cloud_version, has_actuator, has_manifest, has_jar, has_class, ms_sdk_version, jdk_version = values + (file_size, spring_boot_version, spring_cloud_version, has_actuator, + has_manifest, has_jar, has_class, ms_sdk_version, jdk_version) = values tips = ", if you choose to ignore these errors, turn validation off with --disable-validation" if not has_jar and not has_class: @@ -255,7 +270,8 @@ def validate_container_registry_create(cmd, namespace): validate_container_registry(namespace) client = get_client(cmd) try: - container_registry = client.container_registries.get(namespace.resource_group, namespace.service, namespace.name) + container_registry = client.container_registries.get(namespace.resource_group, + namespace.service, namespace.name) if container_registry is not None: raise ClientRequestError('Container Registry {} already exists.'.format(namespace.name)) except ResourceNotFoundError: @@ -292,7 +308,8 @@ def validate_acc_git_url(namespace): def validate_acc_git_refs(namespace): args = [namespace.git_branch, namespace.git_commit, namespace.git_tag] if all(x is None for x in args): - raise ArgumentUsageError("Git Repository configurations at least one of '--git-branch --git-commit --git-tag' should be all provided.") + raise ArgumentUsageError("Git Repository configurations at least one of '--git-branch " + "--git-commit --git-tag' should be all provided.") def validate_git_interval(namespace): @@ -308,7 +325,8 @@ def validate_acs_ssh_or_warn(namespace): host_key_check = namespace.host_key_check if private_key or host_key or host_key_algorithm or host_key_check: logger.warning("SSH authentication only supports SHA-1 signature under ACS restriction. " - "Please refer to https://aka.ms/asa-acs-ssh to understand how to use SSH under this restriction.") + "Please refer to https://aka.ms/asa-acs-ssh to understand how to use SSH " + "under this restriction.") def validate_config_file_patterns(namespace): @@ -326,7 +344,8 @@ def _validate_patterns(patterns): invalid_list = [p for p in pattern_list if not _is_valid_pattern(p)] if len(invalid_list) > 0: logger.warning("Patterns '%s' are invalid.", ','.join(invalid_list)) - raise InvalidArgumentValueError("Patterns should be the collection of patterns separated by comma, each pattern in the format of 'application' or 'application/profile'") + raise InvalidArgumentValueError("Patterns should be the collection of patterns separated by comma, " + "each pattern in the format of 'application' or 'application/profile'") def _is_valid_pattern(pattern): @@ -349,7 +368,8 @@ def _is_valid_app_and_profile_name(pattern): def validate_acs_create(namespace): if namespace.application_configuration_service_generation is not None: if namespace.enable_application_configuration_service is False: - raise ArgumentUsageError("--application-configuration-service-generation can only be set when enable application configuration service.") + raise ArgumentUsageError("--application-configuration-service-generation can only be " + "set when enable application configuration service.") def validate_gateway_update(cmd, namespace): @@ -372,16 +392,20 @@ def validate_api_portal_update(namespace): def validate_dev_tool_portal(namespace): args = [namespace.scopes, namespace.client_id, namespace.client_secret, namespace.metadata_url] if not all(args) and not all(x is None for x in args): - raise ArgumentUsageError("Single Sign On configurations '--scopes --client-id --client-secret --metadata-url' should be all provided or none provided.") + raise ArgumentUsageError("Single Sign On configurations '--scopes --client-id --client-secret " + "--metadata-url' should be all provided or none provided.") if namespace.scopes is not None: namespace.scopes = namespace.scopes.split(",") if namespace.scopes else [] def _validate_sso(namespace): - all_provided = namespace.scope is not None and namespace.client_id is not None and namespace.client_secret is not None and namespace.issuer_uri is not None - none_provided = namespace.scope is None and namespace.client_id is None and namespace.client_secret is None and namespace.issuer_uri is None + all_provided = (namespace.scope is not None and namespace.client_id is not None + and namespace.client_secret is not None and namespace.issuer_uri is not None) + none_provided = (namespace.scope is None and namespace.client_id is None + and namespace.client_secret is None and namespace.issuer_uri is None) if not all_provided and not none_provided: - raise ArgumentUsageError("Single Sign On configurations '--scope --client-id --client-secret --issuer-uri' should be all provided or none provided.") + raise ArgumentUsageError("Single Sign On configurations '--scope --client-id --client-secret " + "--issuer-uri' should be all provided or none provided.") if namespace.scope is not None: namespace.scope = namespace.scope.split(",") if namespace.scope else [] @@ -425,7 +449,8 @@ def _validate_gateway_response_cache_exclusive(namespace): or namespace.response_cache_size is not None or namespace.response_cache_ttl is not None): raise InvalidArgumentValueError( - "Conflict detected: Parameters in ['--response-cache-scope', '--response-cache-scope', '--response-cache-ttl'] " + "Conflict detected: Parameters in ['--response-cache-scope', " + "'--response-cache-scope', '--response-cache-ttl'] " "cannot be set together with '--enable-response-cache false'.") @@ -529,7 +554,8 @@ def validate_buildpack_binding_not_exist(cmd, namespace): if binding_resource is not None: raise ClientRequestError('buildpack Binding {} in builder {} already exists ' 'in resource group {}, service {}. You can edit it by set command.' - .format(namespace.name, namespace.resource_group, namespace.service, namespace.builder_name)) + .format(namespace.name, namespace.resource_group, + namespace.service, namespace.builder_name)) except ResourceNotFoundError: # Excepted case pass diff --git a/src/spring/azext_spring/application_configuration_service.py b/src/spring/azext_spring/application_configuration_service.py index f2c655664f5..7f705ce3b1a 100644 --- a/src/spring/azext_spring/application_configuration_service.py +++ b/src/spring/azext_spring/application_configuration_service.py @@ -3,7 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -# pylint: disable=unused-argument, logging-format-interpolation, protected-access, wrong-import-order, too-many-lines +# pylint: disable=unused-argument, logging-format-interpolation, protected-access, wrong-import-order, too-many-lines, line-too-long import json from azure.cli.core.azclierror import ClientRequestError, ValidationError diff --git a/src/spring/azext_spring/buildpack_binding.py b/src/spring/azext_spring/buildpack_binding.py index a85cad67d1b..edfc63be861 100644 --- a/src/spring/azext_spring/buildpack_binding.py +++ b/src/spring/azext_spring/buildpack_binding.py @@ -3,8 +3,7 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- -# pylint: disable=wrong-import-order -# pylint: disable=line-too-long +# pylint: disable=wrong-import-order, line-too-long from .vendored_sdks.appplatform.v2023_11_01_preview import models from azure.cli.core.util import sdk_no_wait From 05e016fb4f2f90d0c4881430afc33a0f0121e22a Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Mon, 18 Dec 2023 17:04:06 +0800 Subject: [PATCH 18/19] Fix style errors - C0209 --- .../_deployment_source_factory.py | 15 +-- src/spring/azext_spring/_tanzu_component.py | 2 +- src/spring/azext_spring/_transformers.py | 23 +++-- src/spring/azext_spring/_validators.py | 94 +++++++++---------- src/spring/azext_spring/_websocket.py | 4 +- src/spring/azext_spring/apm.py | 4 +- .../application_configuration_service.py | 22 +++-- src/spring/azext_spring/buildpack_binding.py | 16 ++-- src/spring/azext_spring/custom.py | 72 +++++++------- 9 files changed, 121 insertions(+), 131 deletions(-) diff --git a/src/spring/azext_spring/_deployment_source_factory.py b/src/spring/azext_spring/_deployment_source_factory.py index ac8f70daa04..48f113404f7 100644 --- a/src/spring/azext_spring/_deployment_source_factory.py +++ b/src/spring/azext_spring/_deployment_source_factory.py @@ -26,8 +26,7 @@ def validate_source(self, **kwargs): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) runtime_version = (kwargs.get('runtime_version') or kwargs.get('deployment_resource').properties.source.runtime_version) - raise ArgumentUsageError('{} cannot be set when --runtime-version is {}.' - .format(invalid_input_str, runtime_version)) + raise ArgumentUsageError(f'{invalid_input_str} cannot be set when --runtime-version is {runtime_version}.') def format_source(self, deployable_path=None, runtime_version=None, version=None, jvm_options=None, **_): if all(x is None for x in [deployable_path, runtime_version, version, jvm_options]): @@ -59,8 +58,7 @@ def validate_source(self, **kwargs): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) runtime_version = (kwargs.get('runtime_version') or kwargs.get('deployment_resource').properties.source.runtime_version) - raise ArgumentUsageError('{} cannot be set when --runtime-version is {}.' - .format(invalid_input_str, runtime_version)) + raise ArgumentUsageError(f'{invalid_input_str} cannot be set when --runtime-version is {runtime_version}.') def format_source(self, deployable_path=None, runtime_version=None, server_version=None, version=None, jvm_options=None, **_): @@ -95,8 +93,7 @@ def validate_source(self, **kwargs): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) runtime_version = (kwargs.get('runtime_version') or kwargs.get('deployment_resource').properties.source.runtime_version) - raise ArgumentUsageError('{} cannot be set when --runtime-version is {}.' - .format(invalid_input_str, runtime_version)) + raise ArgumentUsageError(f'{invalid_input_str} cannot be set when --runtime-version is {runtime_version}.') def format_source(self, deployable_path=None, main_entry=None, version=None, runtime_version=None, **_): if all(x is None for x in [deployable_path, main_entry, version]): @@ -126,8 +123,7 @@ def validate_source(self, **kwargs): invalid_input = {k: v for k, v in kwargs.items() if k in ['jvm_options', 'main_entry', 'target_module'] and v is not None} # pylint: disable=line-too-long if any(invalid_input): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) - raise ArgumentUsageError('{} cannot be set when --container-image is set.' - .format(invalid_input_str)) + raise ArgumentUsageError(f'{invalid_input_str} cannot be set when --container-image is set.') def format_source(self, version=None, **kwargs): container = self._format_container(**kwargs) @@ -178,8 +174,7 @@ def validate_source(self, **kwargs): invalid_input = {k: v for k, v in kwargs.items() if k in ['jvm_options', 'main_entry'] and v is not None} if any(invalid_input): invalid_input_str = convert_argument_to_parameter_list(invalid_input.keys()) - raise ArgumentUsageError('{} cannot be set when built from source.' - .format(invalid_input_str)) + raise ArgumentUsageError(f'{invalid_input_str} cannot be set when built from source.') def format_source(self, deployable_path=None, target_module=None, runtime_version=None, version=None, **_): if all(x is None for x in [deployable_path, target_module, runtime_version, version]): diff --git a/src/spring/azext_spring/_tanzu_component.py b/src/spring/azext_spring/_tanzu_component.py index 8f909016236..3165461c799 100644 --- a/src/spring/azext_spring/_tanzu_component.py +++ b/src/spring/azext_spring/_tanzu_component.py @@ -45,7 +45,7 @@ def create_application_configuration_service(cmd, client, resource_group, servic acs_resource.properties = models.ConfigurationServiceProperties() if application_configuration_service_generation: acs_resource.properties.generation = application_configuration_service_generation - logger.warning("Create with generation {}".format(application_configuration_service_generation)) + logger.warning(f"Create with generation {application_configuration_service_generation}") else: acs_resource.properties.generation = ConfigurationServiceGeneration.GEN1 logger.warning("Default generation will be Gen1") diff --git a/src/spring/azext_spring/_transformers.py b/src/spring/azext_spring/_transformers.py index 2bafb3d8001..22833daaf8c 100644 --- a/src/spring/azext_spring/_transformers.py +++ b/src/spring/azext_spring/_transformers.py @@ -36,8 +36,7 @@ def transform_app_table_output(result): _apply_deployment_table(item, item['properties']['activeDeployment']) persistentStorage = item['properties']['persistentDisk'] - item['Persistent Storage'] = "{}/{} Gb".format( - persistentStorage['usedInGb'], persistentStorage['sizeInGb']) if persistentStorage['sizeInGb'] else "-" + item['Persistent Storage'] = f"{persistentStorage['usedInGb']}/{persistentStorage['sizeInGb']} Gb" if persistentStorage['sizeInGb'] else "-" if 'addonConfigs' in item['properties']: addon = item['properties']['addonConfigs'] @@ -116,7 +115,7 @@ def _get_registration_state(deployment): return 'N/A' up_number = len( [x for x in instances if x['discoveryStatus'].upper() == 'UP' or x['discoveryStatus'].upper() == 'OUT_OF_SERVICE']) - return "{}/{}".format(up_number, deployment['sku']['capacity']) + return f"{up_number}/{deployment['sku']['capacity']}" def _apply_deployment_table(item, deployment): @@ -128,7 +127,7 @@ def _apply_deployment_table(item, deployment): item['Provisioning State'] = deployment['properties']['provisioningState'] item['CPU'] = deployment['properties']['deploymentSettings']['resourceRequests']['cpu'] item['Memory'] = deployment['properties']['deploymentSettings']['resourceRequests']['memory'] - item['Running Instance'] = "{}/{}".format(running_number, instance_count) if isStarted else "Stopped" + item['Running Instance'] = f"{running_number}/{instance_count}" if isStarted else "Stopped" item['Registered Instance'] = _get_registration_state(deployment) @@ -152,7 +151,7 @@ def _transform_acs_service_registry_output(result): running_number = len( [x for x in instances if x['status'].upper() == "RUNNING"]) item['Provisioning State'] = item['properties']['provisioningState'] - item['Running Instance'] = "{}/{}".format(running_number, instance_count) + item['Running Instance'] = f"{running_number}/{instance_count}" item['CPU'] = item['properties']['resourceRequests']['cpu'] item['Memory'] = item['properties']['resourceRequests']['memory'] @@ -169,7 +168,7 @@ def transform_dev_tool_portal_output(result): item['Provisioning State'] = item['properties']['provisioningState'] item['cpu'] = item['properties']['resourceRequests']['cpu'] item['memory'] = item['properties']['resourceRequests']['memory'] - item['instance'] = '{}/{}'.format(len(item['properties'].get('instances', [])), item['properties']['resourceRequests']['instanceCount']) + item['instance'] = f"{len(item['properties'].get('instances', []))}/{item['properties']['resourceRequests']['instanceCount']}" item['url'] = item['properties'].get('url', '---') return result if is_list else result[0] @@ -185,7 +184,7 @@ def transform_live_view_output(result): for component in item['properties']['components']: item[component['name'] + 'cpu'] = component['resourceRequests']['cpu'] item[component['name'] + 'memory'] = component['resourceRequests']['memory'] - item[component['name'] + 'instance'] = '{}/{}'.format(len(component.get('instances', [])), component['resourceRequests']['instanceCount']) + item[component['name'] + 'instance'] = f"{len(component.get('instances', []))}/{component['resourceRequests']['instanceCount']}" return result if is_list else result[0] @@ -203,7 +202,7 @@ def transform_spring_cloud_gateway_output(result): running_number = len( [x for x in instances if x['status'].upper() == "RUNNING"]) item['Provisioning State'] = item['properties']['provisioningState'] - item['Running Instance'] = "{}/{}".format(running_number, instance_count) + item['Running Instance'] = f"{running_number}/{instance_count}" item['CPU'] = item['properties']['resourceRequests']['cpu'] item['Memory'] = item['properties']['resourceRequests']['memory'] operator = item['properties']['operatorProperties'] @@ -211,7 +210,7 @@ def transform_spring_cloud_gateway_output(result): operator_instances = item['properties']['instances'] or [] operator_running_number = len( [x for x in operator_instances if x['status'].upper() == "RUNNING"]) - item['Operator Running Instance'] = "{}/{}".format(operator_running_number, operator_instance_count) + item['Operator Running Instance'] = f"{operator_running_number}/{operator_instance_count}" item['Operator CPU'] = operator['resourceRequests']['cpu'] item['Operator Memory'] = operator['resourceRequests']['memory'] @@ -231,7 +230,7 @@ def transform_api_portal_output(result): running_number = len( [x for x in instances if x['status'].upper() == "RUNNING"]) item['Provisioning State'] = item['properties']['provisioningState'] - item['Running Instance'] = "{}/{}".format(running_number, instance_count) + item['Running Instance'] = f"{running_number}/{instance_count}" item['CPU'] = item['properties']['resourceRequests']['cpu'] item['Memory'] = item['properties']['resourceRequests']['memory'] @@ -257,7 +256,7 @@ def transform_application_accelerator_output(result): instances = component['instances'] or [] running_number = len( [x for x in instances if x['status'].upper() == "RUNNING"]) - new_entry['Running Instance'] = "{}/{}".format(running_number, instance_count) + new_entry['Running Instance'] = f"{running_number}/{instance_count}" new_entry['CPU'] = component['resourceRequests']['cpu'] new_entry['Memory'] = component['resourceRequests']['memory'] new_result.append(new_entry) @@ -307,7 +306,7 @@ def transform_build_output(result): for item in result: item['Name'] = item['name'] item['Provisioning State'] = item['properties']['provisioningState'] - item['Resource Quota'] = "{}, {}".format(item['properties']['resourceRequests']['cpu'], item['properties']['resourceRequests']['memory']) + item['Resource Quota'] = f"{item['properties']['resourceRequests']['cpu']}, {item['properties']['resourceRequests']['memory']}" item['Builder'] = item['properties']['builder'] return result if is_list else result[0] diff --git a/src/spring/azext_spring/_validators.py b/src/spring/azext_spring/_validators.py index f3634a2d4f5..8f307217e2a 100644 --- a/src/spring/azext_spring/_validators.py +++ b/src/spring/azext_spring/_validators.py @@ -84,31 +84,29 @@ def _validate_terms(cmd, namespace): offer_id=MARKETPLACE_OFFER_ID, plan_id=plan_id) if not term.accepted: - raise InvalidArgumentValueError('Terms for Azure Spring Apps Enterprise is not accepted.\n' - 'Run "az term accept --publisher {} ' - '--product {} ' - '--plan {}" to accept the term.'.format(MARKETPLACE_PUBLISHER_ID, - MARKETPLACE_OFFER_ID, - plan_id)) + raise InvalidArgumentValueError(f'Terms for Azure Spring Apps Enterprise is not accepted.\n' + f'Run "az term accept --publisher {MARKETPLACE_PUBLISHER_ID} ' + f'--product {MARKETPLACE_OFFER_ID} ' + f'--plan {plan_id}" to accept the term.') def _check_tanzu_components_not_enable(cmd, namespace): suffix = ('can only be used for Azure Spring Apps Enterprise. ' 'Please add --sku="Enterprise" to create Enterprise instance.') if namespace.enable_application_configuration_service: - raise ArgumentUsageError('--enable-application-configuration-service {}'.format(suffix)) + raise ArgumentUsageError(f'--enable-application-configuration-service {suffix}') if namespace.enable_service_registry: - raise ArgumentUsageError('--enable-service-registry {}'.format(suffix)) + raise ArgumentUsageError(f'--enable-service-registry {suffix}') if namespace.enable_gateway: - raise ArgumentUsageError('--enable-gateway {}'.format(suffix)) + raise ArgumentUsageError(f'--enable-gateway {suffix}') if namespace.enable_api_portal: - raise ArgumentUsageError('--enable-api-portal {}'.format(suffix)) + raise ArgumentUsageError(f'--enable-api-portal {suffix}') if namespace.enable_application_live_view: - raise ArgumentUsageError('--enable-application-live-view {}'.format(suffix)) + raise ArgumentUsageError(f'--enable-application-live-view {suffix}') if namespace.enable_application_accelerator: - raise ArgumentUsageError('--enable-application-accelerator {}'.format(suffix)) + raise ArgumentUsageError(f'--enable-application-accelerator {suffix}') if namespace.application_configuration_service_generation: - raise ArgumentUsageError('--application-configuration-service-generation {}'.format(suffix)) + raise ArgumentUsageError(f'--application-configuration-service-generation {suffix}') def validate_instance_count(namespace): @@ -121,7 +119,7 @@ def validate_instance_not_existed(client, name, location): availability_parameters = models.NameAvailabilityParameters(type="Microsoft.AppPlatform/Spring", name=name) name_availability = client.services.check_name_availability(location, availability_parameters) if not name_availability.name_available and name_availability.reason == "AlreadyExists": - raise InvalidArgumentValueError("The service name '{}' is already taken.".format(name)) + raise InvalidArgumentValueError(f"The service name '{name}' is already taken.") def validate_name(namespace): @@ -156,7 +154,7 @@ def validate_deployment_name(namespace): def validate_resource_id(namespace): if not is_valid_resource_id(namespace.resource_id): - raise InvalidArgumentValueError("Invalid resource id {}".format(namespace.resource_id)) + raise InvalidArgumentValueError(f"Invalid resource id {namespace.resource_id}") def validate_cosmos_type(namespace): @@ -166,17 +164,17 @@ def validate_cosmos_type(namespace): if type in (ApiType.mongo, ApiType.sql, ApiType.gremlin): if namespace.database_name is None: raise InvalidArgumentValueError( - "Cosmosdb with type {} should specify database name".format(type)) + f"Cosmosdb with type {type} should specify database name") if type == ApiType.cassandra: if namespace.key_space is None: raise InvalidArgumentValueError( - "Cosmosdb with type {} should specify key space".format(type)) + f"Cosmosdb with type {type} should specify key space") if type == ApiType.gremlin: if namespace.key_space is None: raise InvalidArgumentValueError( - "Cosmosdb with type {} should specify collection name".format(type)) + f"Cosmosdb with type {type} should specify collection name") def validate_log_limit(namespace): @@ -340,7 +338,7 @@ def validate_vnet(cmd, namespace): # format the app_subnet and service_runtime_subnet if not is_valid_resource_id(vnet_id): if vnet_id.count('/') > 0: - raise InvalidArgumentValueError('--vnet {0} is not a valid name or resource ID'.format(vnet_id)) + raise InvalidArgumentValueError(f'--vnet {vnet_id} is not a valid name or resource ID') vnet_id = resource_id( subscription=get_subscription_id(cmd.cli_ctx), resource_group=namespace.resource_group, @@ -351,7 +349,7 @@ def validate_vnet(cmd, namespace): else: vnet = parse_resource_id(vnet_id) if vnet['namespace'].lower() != 'microsoft.network' or vnet['type'].lower() != 'virtualnetworks': - raise InvalidArgumentValueError('--vnet {0} is not a valid VirtualNetwork resource ID'.format(vnet_id)) + raise InvalidArgumentValueError(f'--vnet {vnet_id} is not a valid VirtualNetwork resource ID') namespace.app_subnet = _construct_subnet_id(vnet_id, namespace.app_subnet) namespace.service_runtime_subnet = _construct_subnet_id(vnet_id, namespace.service_runtime_subnet) else: @@ -398,7 +396,7 @@ def _validate_subnet(namespace, subnet): else: return if subnet.get("ipConfigurations", None): - raise InvalidArgumentValueError('--{} should not have connected device.'.format(name)) + raise InvalidArgumentValueError(f'--{name} should not have connected device.') address = ip_network(subnet["addressPrefix"], strict=False) if address.prefixlen > limit: error_msg_template = '--{0} should contain at least /{1} address, got /{2}' @@ -463,7 +461,7 @@ def _set_default_cidr_range(address_prefixes): # the last one requires x.x.x.1/16 from API side, it is not a strict address last = candidates[-1] result = [str(x) for x in candidates] - result[-1] = '{0}/16'.format(str(last[1])) + result[-1] = f'{str(last[1])}/16' return ','.join(result) @@ -477,7 +475,7 @@ def _next_range(ip, prefix): address = address + 65536 while address.is_multicast: address = address + 268435456 - return ip_network('{0}/{1}'.format(address, prefix), strict=False) + return ip_network(f'{address}/{prefix}', strict=False) except ValueError: raise InvalidArgumentValueError('Cannot set "reserved-cidr-range" automatically.' 'Please specify "--reserved-cidr-range" with 3 unused CIDR ranges in your ' @@ -486,12 +484,12 @@ def _next_range(ip, prefix): def _parse_vnet_id_from_subnet(subnet_id): if not is_valid_resource_id(subnet_id): - raise InvalidArgumentValueError('{0} is not a valid subnet resource ID'.format(subnet_id)) + raise InvalidArgumentValueError(f'{subnet_id} is not a valid subnet resource ID') subnet = parse_resource_id(subnet_id) if subnet['namespace'].lower() != 'microsoft.network' or \ subnet['type'].lower() != 'virtualnetworks' or \ 'resource_type' not in subnet or subnet['resource_type'].lower() != 'subnets': - raise InvalidArgumentValueError('{0} is not a valid subnet resource ID'.format(subnet_id)) + raise InvalidArgumentValueError(f'{subnet_id} is not a valid subnet resource ID') return resource_id( subscription=subnet['subscription'], resource_group=subnet['resource_group'], @@ -504,11 +502,11 @@ def _parse_vnet_id_from_subnet(subnet_id): def _construct_subnet_id(vnet_id, subnet): if not is_valid_resource_id(subnet): if subnet.count('/'): - raise InvalidArgumentValueError('subnet {0} is not a valid name or resource ID'.format(subnet)) + raise InvalidArgumentValueError(f'subnet {subnet} is not a valid name or resource ID') # subnet name is given return vnet_id + '/subnets/' + subnet if not subnet.lower().startswith(vnet_id.lower()): - raise InvalidArgumentValueError('subnet {0} is not under virtual network {1}'.format(subnet, vnet_id)) + raise InvalidArgumentValueError(f'subnet {subnet} is not under virtual network {vnet_id}') return subnet @@ -529,8 +527,8 @@ def _validate_cidr_range(namespace): for j in range(i + 1, len(ipv4)): if item.overlaps(ipv4[j]): raise InvalidArgumentValueError( - '--reserved-cidr-range should not overlap each other, but {0} and {1} overlapping.' - .format(ranges[i], ranges[j])) + f'--reserved-cidr-range should not overlap each other, ' + f'but {ranges[i]} and {ranges[j]} overlapping.') namespace.reserved_cidr_range = ','.join(ranges) @@ -539,14 +537,14 @@ def _validate_ip(ip, prefix): # Host bits set can be non-zero? Here treat it as valid. ip_address = ip_network(ip, strict=False) if ip_address.version != 4: - raise InvalidArgumentValueError('{0} is not a valid IPv4 CIDR.'.format(ip)) + raise InvalidArgumentValueError(f'{ip} is not a valid IPv4 CIDR.') if ip_address.prefixlen > prefix: raise InvalidArgumentValueError( - '{0} doesn\'t has valid CIDR prefix. ' - ' --reserved-cidr-range should be 3 unused /16 IP ranges.'.format(ip)) + f'{ip} doesn\'t has valid CIDR prefix. ' + f' --reserved-cidr-range should be 3 unused /16 IP ranges.') return ip_address except ValueError: - raise InvalidArgumentValueError('{0} is not a valid CIDR'.format(ip)) + raise InvalidArgumentValueError(f'{ip} is not a valid CIDR') def validate_vnet_required_parameters(namespace): @@ -638,20 +636,20 @@ def validate_jar(namespace): raise InvalidArgumentValueError("Thin jar detected, please check if your artifact is a valid fat jar" + tips) version_number = int(runtime_version[len("Java_"):]) if values["jdk_version"] not in _java_runtime_in_number(): - raise InvalidArgumentValueError("Your java application is compiled with {}, currently the supported " - "java version is Java_8, Java_11, Java_17, you can configure the java runtime " - "with --runtime-version".format("Java_" + str(values["jdk_version"])) + tips) + raise InvalidArgumentValueError(f"Your java application is compiled with {'Java_' + str(values['jdk_version'])}, " + f"currently the supported java version is Java_8, Java_11, Java_17, you can " + f"configure the java runtime with --runtime-version{tips}") if values["jdk_version"] > version_number: telemetry.set_user_fault("invalid_java_runtime") - raise InvalidArgumentValueError("Invalid java runtime, the runtime you configured is {}, the jar you use is " - "compiled with {}, you can configure the java runtime with --runtime-version". - format(runtime_version, "Java_" + str(values["jdk_version"])) + tips) + raise InvalidArgumentValueError(f"Invalid java runtime, the runtime you configured is {runtime_version}, " + f"the jar you use is compiled with {'Java_' + str(values['jdk_version'])}, " + f"you can configure the java runtime with --runtime-version{tips}") # validate spring boot version if values["spring_boot_version"] and values["spring_boot_version"].startswith('1'): telemetry.set_user_fault("old_spring_boot_version") raise InvalidArgumentValueError( - "The spring boot {} you are using is not supported. To get the latest supported " - "versions please refer to: https://aka.ms/ascspringversion".format(values["spring_boot_version"]) + tips) + f"The spring boot {values['spring_boot_version']} you are using is not supported. " + f"To get the latest supported versions please refer to: https://aka.ms/ascspringversion{tips}") # old spring cloud version, need to import ms sdk <= 2.2.1 if values["spring_cloud_version"]: @@ -665,11 +663,11 @@ def validate_jar(namespace): if values["ms_sdk_version"] and values["ms_sdk_version"] <= "2.2.1": telemetry.set_user_fault("old_ms_sdk_version") raise InvalidArgumentValueError( - "The spring-cloud-starter-azure-spring-cloud-client version {} is no longer " - "supported, please remove it or upgrade to a higher version, to get the latest " - "supported versions please refer to: " - "https://mvnrepository.com/artifact/com.microsoft.azure/spring-cloud-starter-azure" - "-spring-cloud-client".format(values["ms_sdk_version"]) + tips) + f"The spring-cloud-starter-azure-spring-cloud-client version {values['ms_sdk_version']} is no longer " + f"supported, please remove it or upgrade to a higher version, to get the latest " + f"supported versions please refer to: " + f"https://mvnrepository.com/artifact/com.microsoft.azure/spring-cloud-starter-azure" + f"-spring-cloud-client{tips}") if not values["has_actuator"]: telemetry.set_user_fault("no_spring_actuator") @@ -764,8 +762,8 @@ def validate_managed_environment(namespace): managed_environment = parse_resource_id(managed_environment_id) if (managed_environment['namespace'].lower() != 'microsoft.app' or managed_environment['type'].lower() != 'managedenvironments'): - raise InvalidArgumentValueError('--managed-environment {0} is not a valid Container App ' - 'Environment resource ID'.format(managed_environment_id)) + raise InvalidArgumentValueError(f'--managed-environment {managed_environment_id} is not a valid ' + f'Container App Environment resource ID') def validate_server_version(cmd, namespace): diff --git a/src/spring/azext_spring/_websocket.py b/src/spring/azext_spring/_websocket.py index 22633836603..00f88a395dd 100644 --- a/src/spring/azext_spring/_websocket.py +++ b/src/spring/azext_spring/_websocket.py @@ -24,7 +24,7 @@ def __init__(self, url, token): self._url = url self._socket = websocket.WebSocket(enable_multithread=True) logger.info("Attempting to connect to %s", self._url) - self._socket.connect(self._url, header=["Authorization: Bearer %s" % self._token]) + self._socket.connect(self._url, header=[f"Authorization: Bearer {self._token}"]) self.is_connected = True def disconnect(self): @@ -54,7 +54,7 @@ def recv_remote(connection: WebSocketConnection): pass # Do nothing for this control byte else: connection.disconnect() - raise CLIInternalError("Unexpected message received: %d" % control_byte) + raise CLIInternalError(f"Unexpected message received: {control_byte}") def send_stdin(connection: WebSocketConnection): diff --git a/src/spring/azext_spring/apm.py b/src/spring/azext_spring/apm.py index 6d20c2d78b0..9e724e1833e 100644 --- a/src/spring/azext_spring/apm.py +++ b/src/spring/azext_spring/apm.py @@ -140,7 +140,7 @@ def _get_connection_string_from_app_insights(cmd, resource_group, app_insights): # Raise exception when connection string not found in this scenario. if not connection_string: raise InvalidArgumentValueError( - "Cannot find Connection string from application insights:{}".format(app_insights)) + f"Cannot find Connection string from application insights:{app_insights}") return connection_string @@ -151,7 +151,7 @@ def _get_app_insights_connection_string(cli_ctx, resource_group, name): if not appinsights or not appinsights.connection_string: raise ResourceNotFoundError( - "Application Insights {} under resource group {} was not found.".format(name, resource_group)) + f"Application Insights {name} under resource group {resource_group} was not found.") return appinsights.connection_string diff --git a/src/spring/azext_spring/application_configuration_service.py b/src/spring/azext_spring/application_configuration_service.py index 7f705ce3b1a..1daa2a27fac 100644 --- a/src/spring/azext_spring/application_configuration_service.py +++ b/src/spring/azext_spring/application_configuration_service.py @@ -30,7 +30,7 @@ def application_configuration_service_create(cmd, client, service, resource_grou properties = models.ConfigurationServiceProperties(generation=generation) acs_resource = models.ConfigurationServiceResource(properties=properties) - logger.warning("Create with generation {}".format(acs_resource.properties.generation)) + logger.warning(f"Create with generation {acs_resource.properties.generation}") return client.configuration_services.begin_create_or_update(resource_group, service, DEFAULT_NAME, acs_resource) @@ -39,7 +39,7 @@ def application_configuration_service_update(cmd, client, service, resource_grou acs_resource = client.configuration_services.get(resource_group, service, DEFAULT_NAME) if generation is not None: acs_resource.properties.generation = generation - logger.warning("Updating with generation {}".format(generation)) + logger.warning(f"Updating with generation {generation}") else: acs_resource.properties.generation = ConfigurationServiceGeneration.GEN1 logger.warning("Default generation will be Gen1") @@ -79,7 +79,7 @@ def application_configuration_service_git_add(cmd, client, service, resource_gro acs_resource = _get_or_default_acs_resource(client, resource_group, service) repos = acs_resource.properties.settings.git_property.repositories if next((r for r in repos if r.name == name), None) is not None: - raise ValidationError("Repo '{}' already exists.".format(name)) + raise ValidationError(f"Repo '{name}' already exists.") repos.append(repo) acs_resource.properties.settings.git_property.repositories = repos @@ -144,7 +144,7 @@ def _acs_bind_or_unbind_app(cmd, client, service, resource_group, app_name, enab app.properties.addon_configs = _get_app_addon_configs_with_acs(app.properties.addon_configs) if (app.properties.addon_configs[APPLICATION_CONFIGURATION_SERVICE_NAME][RESOURCE_ID] != "") == enabled: - logger.warning('App "{}" has been {}binded'.format(app_name, '' if enabled else 'un')) + logger.warning(f'App "{app_name}" has been {"" if enabled else "un"}binded') return app acs_id = resource_id( @@ -177,11 +177,13 @@ def _get_cert_resource_id_by_name(cmd, resource_group, service, ca_cert_name): ca_cert_resource_id = None if ca_cert_name: subscription = get_subscription_id(cmd.cli_ctx) - ca_cert_resource_id = "/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/certificates/{}".format(subscription, resource_group, service, ca_cert_name) + ca_cert_resource_id = f"/subscriptions/{subscription}/resourceGroups/{resource_group}/providers/Microsoft.AppPlatform/Spring/{service}/certificates/{ca_cert_name}" return ca_cert_resource_id -def _replace_repo_with_input(repo, patterns, uri, label, search_paths, username, password, host_key, host_key_algorithm, private_key, strict_host_key_checking, ca_cert_resource_id): +def _replace_repo_with_input(repo, patterns, uri, label, search_paths, username, password, + host_key, host_key_algorithm, private_key, + strict_host_key_checking, ca_cert_resource_id): if patterns: patterns = patterns.split(",") if search_paths: @@ -206,7 +208,7 @@ def _replace_repo_with_input(repo, patterns, uri, label, search_paths, username, def _get_existing_repo(repos, name): repo = next((r for r in repos if r.name == name), None) if not repo: - raise ClientRequestError("Repo '{}' not found.".format(name)) + raise ClientRequestError(f"Repo '{name}' not found.") return repo @@ -254,11 +256,13 @@ def _validate_acs_settings(client, resource_group, service, acs_settings): try: result = sdk_no_wait(False, client.configuration_services.begin_validate, resource_group, service, DEFAULT_NAME, acs_settings).result() except Exception as err: # pylint: disable=broad-except - raise ClientRequestError("{0}. You may raise a support ticket if needed by the following link: https://docs.microsoft.com/azure/spring-cloud/spring-cloud-faq?pivots=programming-language-java#how-can-i-provide-feedback-and-report-issues".format(err)) + raise ClientRequestError(f"{err}. You may raise a support ticket if needed by the following " + f"link: https://docs.microsoft.com/azure/spring-cloud/spring-cloud-faq?pivots=programming-language-java#how-can-i-provide-feedback-and-report-issues") if result is not None and result.git_property_validation_result is not None: git_result = result.git_property_validation_result if not git_result.is_valid: validation_result = git_result.git_repos_validation_result filter_result = [{'name': x.name, 'messages': x.messages} for x in validation_result if len(x.messages) > 0] - raise ClientRequestError("Application Configuration Service settings contain errors.\n{}".format(json.dumps(filter_result, indent=2))) + result = json.dumps(filter_result, indent=2) + raise ClientRequestError(f"Application Configuration Service settings contain errors.\n{result}") diff --git a/src/spring/azext_spring/buildpack_binding.py b/src/spring/azext_spring/buildpack_binding.py index edfc63be861..d4dfa1dbb5e 100644 --- a/src/spring/azext_spring/buildpack_binding.py +++ b/src/spring/azext_spring/buildpack_binding.py @@ -29,9 +29,9 @@ def create_or_update_buildpack_binding(cmd, client, resource_group, service, 'Use CLI command --"az spring build-service builder show-deployments" to view the app deployment list of the builder.') if not builder_name: builder_name = DEFAULT_BUILDER_NAME - logger.warning('Option --builder-name is not provided, will use default builder name "{}".'.format(builder_name)) + logger.warning(f'Option --builder-name is not provided, will use default builder name "{builder_name}".') - logger.warning('[1/1] Creating or updating to buildpack binding for builder "{}", (this operation can take a while to complete).'.format(builder_name)) + logger.warning(f'[1/1] Creating or updating to buildpack binding for builder "{builder_name}", (this operation can take a while to complete).') binding_resource = _build_buildpack_binding_resource(type, properties, secrets) return sdk_no_wait(False, client.buildpack_binding.begin_create_or_update, resource_group, @@ -41,7 +41,7 @@ def create_or_update_buildpack_binding(cmd, client, resource_group, service, def buildpack_binding_show(cmd, client, resource_group, service, name, builder_name=None): if not builder_name: builder_name = DEFAULT_BUILDER_NAME - logger.warning('Option --builder-name is not provided, will use default builder name "{}".'.format(builder_name)) + logger.warning(f'Option --builder-name is not provided, will use default builder name "{builder_name}".') return client.buildpack_binding.get(resource_group, service, DEFAULT_BUILD_SERVICE_NAME, builder_name, name) @@ -50,7 +50,7 @@ def buildpack_binding_show(cmd, client, resource_group, service, name, builder_n def buildpack_binding_list(cmd, client, resource_group, service, builder_name=None): if not builder_name: builder_name = DEFAULT_BUILDER_NAME - logger.warning('Option --builder-name is not provided, will use default builder name "{}".'.format(builder_name)) + logger.warning(f'Option --builder-name is not provided, will use default builder name "{builder_name}".') return client.buildpack_binding.list(resource_group, service, DEFAULT_BUILD_SERVICE_NAME, builder_name) @@ -61,9 +61,9 @@ def buildpack_binding_delete(cmd, client, resource_group, service, name, builder 'Use CLI command --"az spring build-service builder show-deployments" to view the app deployment list of the builder.') if not builder_name: builder_name = DEFAULT_BUILDER_NAME - logger.warning('Option --builder-name is not provided, will use default builder name "{}".'.format(builder_name)) + logger.warning(f'Option --builder-name is not provided, will use default builder name "{builder_name}".') - logger.warning('[1/1] Deleting buildpack binding for builder "{}", (this operation can take a while to complete).'.format(builder_name)) + logger.warning(f'[1/1] Deleting buildpack binding for builder "{builder_name}", (this operation can take a while to complete).') return sdk_no_wait(False, client.buildpack_binding.begin_delete, resource_group, service, DEFAULT_BUILD_SERVICE_NAME, builder_name, name) @@ -143,7 +143,7 @@ def _get_connection_string_from_app_insights(cmd, resource_group, app_insights): # Raise exception when connection string not found in this scenario. if not connection_string: raise InvalidArgumentValueError( - "Cannot find Connection string from application insights:{}".format(app_insights)) + f"Cannot find Connection string from application insights:{app_insights}") return connection_string @@ -153,7 +153,7 @@ def _get_app_insights_connection_string(cli_ctx, resource_group, name): appinsights = appinsights_client.components.get(resource_group, name) if not appinsights or not appinsights.connection_string: - raise ResourceNotFoundError("App Insights {} under resource group {} was not found.".format(name, resource_group)) + raise ResourceNotFoundError(f"App Insights {name} under resource group {resource_group} was not found.") return appinsights.connection_string diff --git a/src/spring/azext_spring/custom.py b/src/spring/azext_spring/custom.py index 7babbb4555c..36e71b84c59 100644 --- a/src/spring/azext_spring/custom.py +++ b/src/spring/azext_spring/custom.py @@ -215,7 +215,7 @@ def spring_start(cmd, client, resource_group, name, no_wait=False): state = resource.properties.provisioning_state power_state = resource.properties.power_state if state != "Succeeded" or power_state != "Stopped": - raise ClientRequestError("Service is in Provisioning State({}) and Power State({}), starting cannot be performed.".format(state, power_state)) + raise ClientRequestError(f"Service is in Provisioning State({state}) and Power State({power_state}), starting cannot be performed.") return sdk_no_wait(no_wait, client.services.begin_start, resource_group_name=resource_group, service_name=name) @@ -224,7 +224,7 @@ def spring_stop(cmd, client, resource_group, name, no_wait=False): state = resource.properties.provisioning_state power_state = resource.properties.power_state if state != "Succeeded" or power_state != "Running": - raise ClientRequestError("Service is in Provisioning State({}) and Power State({}), stopping cannot be performed.".format(state, power_state)) + raise ClientRequestError(f"Service is in Provisioning State({state}) and Power State({power_state}), stopping cannot be performed.") return sdk_no_wait(no_wait, client.services.begin_stop, resource_group_name=resource_group, service_name=name) @@ -233,7 +233,7 @@ def spring_flush_vnet_dns_setting(cmd, client, resource_group, name, no_wait=Fal state = resource.properties.provisioning_state power_state = resource.properties.power_state if state != "Succeeded" or power_state != "Running": - raise ClientRequestError("Service is in Provisioning State({}) and Power State({}), flush vnet dns setting cannot be performed.".format(state, power_state)) + raise ClientRequestError(f"Service is in Provisioning State({state}) and Power State({power_state}), flush vnet dns setting cannot be performed.") return sdk_no_wait(no_wait, client.services.begin_flush_vnet_dns_setting, resource_group_name=resource_group, service_name=name) @@ -263,8 +263,8 @@ def list_keys(cmd, client, resource_group, name, app=None, deployment=None): deployment_resource = deployment_get(cmd, client, resource_group, name, app, deployment) \ if deployment else app_get(cmd, client, resource_group, name, app).properties.active_deployment if deployment_resource: - keys.primary_test_endpoint = "{}/{}/{}/".format(keys.primary_test_endpoint, app, deployment_resource.name) - keys.secondary_test_endpoint = "{}/{}/{}/".format(keys.secondary_test_endpoint, app, deployment_resource.name) + keys.primary_test_endpoint = f"{keys.primary_test_endpoint}/{app}/{deployment_resource.name}/" + keys.secondary_test_endpoint = f"{keys.secondary_test_endpoint}/{app}/{deployment_resource.name}/" return keys @@ -312,7 +312,7 @@ def app_append_persistent_storage(cmd, client, resource_group, service, name, app.properties.custom_persistent_disks = custom_persistent_disks app.properties.secrets = None - logger.warning("[1/1] updating app '{}'".format(name)) + logger.warning(f"[1/1] updating app '{name}'") poller = client.apps.begin_update( resource_group, service, name, app) @@ -337,7 +337,7 @@ def app_start(cmd, client, name, deployment=None, no_wait=False): - logger.warning("Successfully triggered the action 'start' for the app '{}'".format(name)) + logger.warning(f"Successfully triggered the action 'start' for the app '{name}'") return sdk_no_wait(no_wait, client.deployments.begin_start, resource_group, service, name, deployment.name) @@ -348,20 +348,20 @@ def app_stop(cmd, client, name, deployment=None, no_wait=False): - logger.warning("Successfully triggered the action 'stop' for the app '{}'".format(name)) + logger.warning(f"Successfully triggered the action 'stop' for the app '{name}'") return sdk_no_wait(no_wait, client.deployments.begin_stop, resource_group, service, name, deployment.name) def deployment_enable_remote_debugging(cmd, client, resource_group, service, name, remote_debugging_port=None, deployment=None, no_wait=False): - logger.warning("Enable remote debugging for the app '{}', deployment '{}'".format(name, deployment.name)) + logger.warning(f"Enable remote debugging for the app '{name}', deployment '{deployment.name}'") remote_debugging_payload = models.RemoteDebuggingPayload(port=remote_debugging_port) return sdk_no_wait(no_wait, client.deployments.begin_enable_remote_debugging, resource_group, service, name, deployment.name, remote_debugging_payload) def deployment_disable_remote_debugging(cmd, client, resource_group, service, name, deployment=None, no_wait=False): - logger.warning("Disable remote debugging for the app '{}', deployment '{}'".format(name, deployment.name)) + logger.warning(f"Disable remote debugging for the app '{name}', deployment '{deployment.name}'") return sdk_no_wait(no_wait, client.deployments.begin_disable_remote_debugging, resource_group, service, name, deployment.name) @@ -376,7 +376,7 @@ def app_restart(cmd, client, name, deployment=None, no_wait=False): - logger.warning("Successfully triggered the action 'restart' for the app '{}'".format(name)) + logger.warning(f"Successfully triggered the action 'restart' for the app '{name}'") return sdk_no_wait(no_wait, client.deployments.begin_restart, resource_group, service, name, deployment.name) @@ -474,8 +474,7 @@ def parse_metadata_flags(metadata_list, metadata_def): if len(key_val) != 2: raise InvalidArgumentValueError("Metadata must be in format \"= = ...\".") if key_val[0] in metadata_def: - raise InvalidArgumentValueError("Duplicate metadata \"{metadata}\" found, metadata keys must be unique.".format( - metadata=key_val[0])) + raise InvalidArgumentValueError(f"Duplicate metadata \"{key_val[0]}\" found, metadata keys must be unique.") metadata_def[key_val[0]] = key_val[1] return metadata_def @@ -493,8 +492,7 @@ def parse_auth_flags(auth_list): "Auth parameters must be in format \"= = ...\".") if key_val[0] in auth_pairs: raise InvalidArgumentValueError( - "Duplicate trigger parameter \"{param}\" found, trigger paramaters must be unique.".format( - param=key_val[0])) + f"Duplicate trigger parameter \"{key_val[0]}\" found, trigger paramaters must be unique.") auth_pairs[key_val[0]] = key_val[1] for key, value in auth_pairs.items(): @@ -507,7 +505,7 @@ def parse_auth_flags(auth_list): def app_get_build_log(cmd, client, resource_group, service, name, deployment=None): if deployment.properties.source.type != "Source": - raise CLIError("{} deployment has no build logs.".format(deployment.properties.source.type)) + raise CLIError(f"{deployment.properties.source.type} deployment has no build logs.") return stream_logs(client.deployments, resource_group, service, name, deployment.name) @@ -522,13 +520,12 @@ def app_tail_log_internal(cmd, client, resource_group, service, name, format_json=None, timeout=None, get_app_log=None): if not instance: if not deployment.properties.instances: - raise CLIError("No instances found for deployment '{0}' in app '{1}'".format( - deployment.name, name)) + raise CLIError(f"No instances found for deployment '{deployment.name}' in app '{name}'") instances = deployment.properties.instances if len(instances) > 1: logger.warning("Multiple app instances found:") for temp_instance in instances: - logger.warning("{}".format(temp_instance.name)) + logger.warning(temp_instance.name) logger.warning("Please use '-i/--instance' parameter to specify the instance name") return None instance = instances[0].name @@ -540,8 +537,7 @@ def app_tail_log_internal(cmd, client, resource_group, service, name, token = creds[1] subscriptionId = get_subscription_id(cmd.cli_ctx) hostname = get_proxy_api_endpoint(cmd.cli_ctx, resource) - streaming_url = "https://{}/proxy/logstream/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/apps/{}/deployments/{}/instances/{}".format( - hostname, subscriptionId, resource_group, service, name, deployment.name, instance) + streaming_url = f"https://{hostname}/proxy/logstream/subscriptions/{subscriptionId}/resourceGroups/{resource_group}/providers/Microsoft.AppPlatform/Spring/{service}/apps/{name}/deployments/{deployment.name}/instances/{instance}" params = {} params["tailLines"] = lines params["tenantId"] = tenant @@ -552,9 +548,9 @@ def app_tail_log_internal(cmd, client, resource_group, service, name, else: log_stream = LogStream(client, resource_group, service) if not log_stream: - raise CLIError("To use the log streaming feature, please enable the test endpoint by running 'az spring test-endpoint enable -n {0} -g {1}'".format(service, resource_group)) - streaming_url = "https://{0}/api/logstream/apps/{1}/instances/{2}".format( - log_stream.base_url, name, instance) + raise CLIError(f"To use the log streaming feature, please enable the test endpoint by " + f"running 'az spring test-endpoint enable -n {service} -g {resource_group}'") + streaming_url = f"https://{log_stream.base_url}/api/logstream/apps/{name}/instances/{instance}" params = {} params["tailLines"] = lines params["limitBytes"] = limit @@ -565,7 +561,7 @@ def app_tail_log_internal(cmd, client, resource_group, service, name, auth = HTTPBasicAuth("primary", log_stream.primary_key) exceptions = [] - streaming_url += "?{}".format(parse.urlencode(params)) if params else "" + streaming_url += f"?{parse.urlencode(params)}" if params else "" t = Thread(target=get_app_log, args=( streaming_url, auth, format_json, exceptions)) t.daemon = True @@ -616,7 +612,7 @@ def app_append_loaded_public_certificate(cmd, client, resource_group, service, n app_resource.properties.loaded_certificates = loaded_certificates app_resource.properties.secrets = None - logger.warning("[1/1] updating app '{}'".format(name)) + logger.warning(f"[1/1] updating app '{name}'") poller = client.apps.begin_update( resource_group, service, name, app_resource) @@ -633,15 +629,15 @@ def _validate_instance_count(sku, instance_count=None): if sku == "ENTERPRISE": if instance_count > 1000: raise InvalidArgumentValueError( - "Enterprise SKU can have at most 1000 app instances in total, but got '{}'".format(instance_count)) + f"Enterprise SKU can have at most 1000 app instances in total, but got '{instance_count}'") if sku == "STANDARD": if instance_count > 500: raise CLIError( - "Standard SKU can have at most 500 app instances in total, but got '{}'".format(instance_count)) + f"Standard SKU can have at most 500 app instances in total, but got '{instance_count}'") if sku == "BASIC": if instance_count > 25: raise CLIError( - "Basic SKU can have at most 25 app instances in total, but got '{}'".format(instance_count)) + f"Basic SKU can have at most 25 app instances in total, but got '{instance_count}'") def deployment_list(cmd, client, resource_group, service, app): @@ -697,7 +693,7 @@ def validate_config_server_settings(client, resource_group, name, config_server_ try: result = sdk_no_wait(False, client.begin_validate, resource_group, name, config_server_settings).result() except Exception as err: # pylint: disable=broad-except - raise CLIError("{0}. You may raise a support ticket if needed by the following link: https://docs.microsoft.com/azure/spring-cloud/spring-cloud-faq?pivots=programming-language-java#how-can-i-provide-feedback-and-report-issues".format(err)) + raise CLIError(f"{err}. You may raise a support ticket if needed by the following link: https://docs.microsoft.com/azure/spring-cloud/spring-cloud-faq?pivots=programming-language-java#how-can-i-provide-feedback-and-report-issues") if not result.is_valid: for item in result.details or []: @@ -874,7 +870,7 @@ def config_repo_add(cmd, client, resource_group, name, uri, repo_name, if git_property.repositories: repos = [repo for repo in git_property.repositories if repo.name == repo_name] if repos: - raise CLIError("Repo '{}' already exists.".format(repo_name)) + raise CLIError(f"Repo '{repo_name}' already exists.") else: git_property.repositories = [] @@ -908,12 +904,12 @@ def config_repo_delete(cmd, client, resource_group, name, repo_name): config_server_resource = client.get(resource_group, name) config_server = config_server_resource.properties.config_server if not config_server or not config_server.git_property or not config_server.git_property.repositories: - raise CLIError("Repo '{}' not found.".format(repo_name)) + raise CLIError(f"Repo '{repo_name}' not found.") git_property = config_server.git_property repository = [repo for repo in git_property.repositories if repo.name == repo_name] if not repository: - raise CLIError("Repo '{}' not found.".format(repo_name)) + raise CLIError(f"Repo '{repo_name}' not found.") git_property.repositories.remove(repository[0]) @@ -943,11 +939,11 @@ def config_repo_update(cmd, client, resource_group, name, repo_name, config_server_resource = client.get(resource_group, name) config_server = config_server_resource.properties.config_server if not config_server or not config_server.git_property or not config_server.git_property.repositories: - raise CLIError("Repo '{}' not found.".format(repo_name)) + raise CLIError(f"Repo '{repo_name}' not found.") git_property = config_server.git_property repository = [repo for repo in git_property.repositories if repo.name == repo_name] if not repository: - raise CLIError("Repo '{}' not found.".format(repo_name)) + raise CLIError(f"Repo '{repo_name}' not found.") if search_paths: search_paths = search_paths.split(",") @@ -1025,8 +1021,7 @@ def binding_cosmos_add(cmd, client, resource_group, service, app, name, try: primary_key = _get_cosmosdb_primary_key(cmd.cli_ctx, resource_id) except: - raise CLIError( - "Couldn't get cosmosdb {}'s primary key".format(resource_name)) + raise CLIError(f"Couldn't get cosmosdb {resource_name}'s primary key") properties = models.BindingResourceProperties( resource_name=resource_name, @@ -1054,8 +1049,7 @@ def binding_cosmos_update(cmd, client, resource_group, service, app, name, try: primary_key = _get_cosmosdb_primary_key(cmd.cli_ctx, resource_id) except: - raise CLIError( - "Couldn't get cosmosdb {}'s primary key".format(resource_name)) + raise CLIError(f"Couldn't get cosmosdb {resource_name}'s primary key") properties = models.BindingResourceProperties( key=primary_key, From e666bccd0835d532484dd13dbf5def9c1da716c7 Mon Sep 17 00:00:00 2001 From: Moary Chen Date: Tue, 19 Dec 2023 08:05:02 +0800 Subject: [PATCH 19/19] Fix style errors - C0209 --- src/spring/azext_spring/_app_factory.py | 2 +- src/spring/azext_spring/_app_validator.py | 6 +-- .../azext_spring/_buildservices_factory.py | 21 +++++------ .../_deployment_deployable_factory.py | 4 +- src/spring/azext_spring/_params.py | 32 ++++++++-------- src/spring/azext_spring/_stream_utils.py | 4 +- src/spring/azext_spring/_utils.py | 8 ++-- src/spring/azext_spring/app.py | 37 ++++++++----------- .../azext_spring/application_accelerator.py | 7 ++-- src/spring/azext_spring/custom.py | 36 ++++++++---------- src/spring/azext_spring/service_registry.py | 2 +- 11 files changed, 74 insertions(+), 85 deletions(-) diff --git a/src/spring/azext_spring/_app_factory.py b/src/spring/azext_spring/_app_factory.py index 65b4193f4b3..e5c5e406fd5 100644 --- a/src/spring/azext_spring/_app_factory.py +++ b/src/spring/azext_spring/_app_factory.py @@ -167,7 +167,7 @@ def _load_secrets_config(self, secrets=None, **_): raise InvalidArgumentValueError("Secrets must be in format \"= = ...\".") if key_val[0] in secret_pairs: raise InvalidArgumentValueError( - "Duplicate secret \"{secret}\" found, secret names must be unique.".format(secret=key_val[0])) + f"Duplicate secret \"{key_val[0]}\" found, secret names must be unique.") secret_pairs[key_val[0]] = key_val[1] secret_var_def = [] diff --git a/src/spring/azext_spring/_app_validator.py b/src/spring/azext_spring/_app_validator.py index 53913dd96f1..097e03240a1 100644 --- a/src/spring/azext_spring/_app_validator.py +++ b/src/spring/azext_spring/_app_validator.py @@ -75,14 +75,14 @@ def ensure_not_active_deployment(cmd, namespace): client = cf_spring(cmd.cli_ctx) deployment = _ensure_deployment_exist(client, namespace.resource_group, namespace.service, namespace.name, namespace.deployment) if deployment.properties.active: - raise InvalidArgumentValueError('Deployment {} is already the production deployment'.format(deployment.name)) + raise InvalidArgumentValueError(f'Deployment {deployment.name} is already the production deployment') def _ensure_deployment_exist(client, resource_group, service, app, deployment): try: return client.deployments.get(resource_group, service, app, deployment) except CloudError: - raise InvalidArgumentValueError('Deployment {} not found under app {}'.format(deployment, app)) + raise InvalidArgumentValueError(f'Deployment {deployment} not found under app {app}') def _ensure_active_deployment_exist_and_get(client, resource_group, service, name): @@ -97,7 +97,7 @@ def _get_active_deployment(client, resource_group, service, name): deployments = client.deployments.list(resource_group, service, name) return next(iter(x for x in deployments if x.properties.active), None) except ResourceNotFoundError: - raise InvalidArgumentValueError('App {} not found'.format(name)) + raise InvalidArgumentValueError(f'App {name} not found') def validate_deloy_path(cmd, namespace): diff --git a/src/spring/azext_spring/_buildservices_factory.py b/src/spring/azext_spring/_buildservices_factory.py index 62aa0837fcc..a8dbb3c384d 100644 --- a/src/spring/azext_spring/_buildservices_factory.py +++ b/src/spring/azext_spring/_buildservices_factory.py @@ -186,19 +186,19 @@ def _start_build_stage_log(self, result, pod, stage_name): return stage = next(iter(x for x in result.properties.build_stages if x.name == stage_name), None) if not stage: - logger.debug('Not found the stage {} in latest response'.format(stage_name)) - raise 'Not found the stage {} in latest response'.format(stage_name) + logger.debug(f'Not found the stage {stage_name} in latest response') + raise f'Not found the stage {stage_name} in latest response' self._print_build_stage_log(pod, stage) def _print_build_stage_log(self, pod, stage): if stage.status == 'NotStarted': - logger.debug('Build stage {} not started yet.'.format(stage.name)) - raise InvalidArgumentValueError('Build stage {} not started yet.'.format(stage.name)) + logger.debug(f'Build stage {stage.name} not started yet.') + raise InvalidArgumentValueError(f'Build stage {stage.name} not started yet.') log_stream = self._get_log_stream() - url = 'https://{}/api/logstream/buildpods/{}/stages/{}?follow=true'.format(log_stream.base_url, pod, stage.name) + url = f'https://{log_stream.base_url}/api/logstream/buildpods/{pod}/stages/{stage.name}?follow=true' with requests.get(url, stream=True, auth=HTTPBasicAuth("primary", log_stream.primary_key)) as response: if response.status_code == 200: - logger.debug('start to stream log for stage {}'.format(stage.name)) + logger.debug(f'start to stream log for stage {stage.name}') self.progress_bar and self.progress_bar.end() std_encoding = sys.stdout.encoding for content in response.iter_content(): @@ -206,16 +206,15 @@ def _print_build_stage_log(self, pod, stage): sys.stdout.write(content.decode(encoding='utf-8', errors='replace') .encode(std_encoding, errors='replace') .decode(std_encoding, errors='replace')) - logger.debug('End to stream log for stage {}'.format(stage.name)) + logger.debug(f'End to stream log for stage {stage.name}') elif response.status_code == 400: - logger.debug('Failed to stream build log with response {}'.format(response.content)) + logger.debug(f'Failed to stream build log with response {response.content}') raise InvalidArgumentValueError(response.content) else: status_code = response.status_code if response else 'Unknown' content = response.content if response else 'Unknown' - logger.debug('Failed to stream build log with response {}: {}'.format(status_code, content)) - raise "Failed to get build logs with status code '{}' and reason '{}'".format( - status_code, content) + logger.debug(f'Failed to stream build log with response {status_code}: {content}') + raise f"Failed to get build logs with status code '{status_code}' and reason '{content}'" def _get_log_stream(self): if not self.log_stream: diff --git a/src/spring/azext_spring/_deployment_deployable_factory.py b/src/spring/azext_spring/_deployment_deployable_factory.py index 3dd4a39bbeb..de97c378413 100644 --- a/src/spring/azext_spring/_deployment_deployable_factory.py +++ b/src/spring/azext_spring/_deployment_deployable_factory.py @@ -62,13 +62,13 @@ def get_total_deploy_steps(self, **_): return 3 def build_deployable_path(self, **kwargs): - logger.warning('[1/{}] Requesting for upload URL.'.format(kwargs['total_steps'])) + logger.warning(f'[1/{kwargs["total_steps"]}] Requesting for upload URL.') upload_info = self.client.apps.get_resource_upload_url(self.resource_group, self.service, self.app) if not upload_info.upload_url: raise InvalidArgumentValueError('Failed to get a SAS URL to upload context.') - logger.warning('[2/{}] Uploading package to blob.'.format(kwargs['total_steps'])) + logger.warning(f'[2/{kwargs["total_steps"]}] Uploading package to blob.') self._get_uploader(upload_url=upload_info.upload_url).upload_and_build(**kwargs) return upload_info.relative_path diff --git a/src/spring/azext_spring/_params.py b/src/spring/azext_spring/_params.py index 8c099ec915a..27d673d8fed 100644 --- a/src/spring/azext_spring/_params.py +++ b/src/spring/azext_spring/_params.py @@ -510,7 +510,7 @@ def prepare_logs_argument(c): '--main-entry', '-m'], help="The path to the .NET executable relative to zip root.") for scope in ['update', 'deployment create', 'deploy']: - with self.argument_context('spring app {}'.format(scope)) as c: + with self.argument_context(f'spring app {scope}') as c: c.argument('config_file_patterns', help="(Enterprise Tier Only) Config file patterns separated with \',\' to decide which patterns " "of Application Configuration Service will be used. Use '\"\"' to clear existing configurations.", @@ -776,7 +776,7 @@ def prepare_logs_argument(c): c.argument('password', help="The container registry password.", validator=validate_container_registry_update) for scope in ['show', 'delete']: - with self.argument_context('spring container-registry {}'.format(scope)) as c: + with self.argument_context(f'spring container-registry {scope}') as c: c.argument('name', help="The container registry name.") with self.argument_context('spring build-service') as c: @@ -789,7 +789,7 @@ def prepare_logs_argument(c): c.argument('service', service_name_type, validator=validate_central_build_instance) for scope in ['create', 'update']: - with self.argument_context('spring build-service build {}'.format(scope)) as c: + with self.argument_context(f'spring build-service build {scope}') as c: c.argument('build_env', build_env_type) c.argument('source_path', arg_type=source_path_type, validator=validate_source_path) c.argument('artifact_path', help='Deploy the specified pre-built artifact (jar or netcore zip).', validator=validate_artifact_path) @@ -826,7 +826,7 @@ def prepare_logs_argument(c): c.argument('service', service_name_type, validator=only_support_enterprise) for scope in ['create', 'update']: - with self.argument_context('spring build-service builder {}'.format(scope)) as c: + with self.argument_context(f'spring build-service builder {scope}') as c: c.argument('builder_json', help="The JSON array of builder.", validator=validate_builder_resource) c.argument('builder_file', help="The file path of JSON array of builder.", validator=validate_builder_resource) @@ -837,16 +837,16 @@ def prepare_logs_argument(c): c.argument('name', help="The builder name.", validator=validate_builder_update) for scope in ['show', 'delete']: - with self.argument_context('spring build-service builder {}'.format(scope)) as c: + with self.argument_context(f'spring build-service builder {scope}') as c: c.argument('name', help="The builder name.") for scope in ['application-configuration-service', 'service-registry', 'gateway', 'api-portal', 'application-live-view', 'dev-tool', 'application-accelerator']: - with self.argument_context('spring {}'.format(scope)) as c: + with self.argument_context(f'spring {scope}') as c: c.argument('service', service_name_type, validator=only_support_enterprise) for scope in ['dev-tool create', 'dev-tool update']: - with self.argument_context('spring {}'.format(scope)) as c: + with self.argument_context(f'spring {scope}') as c: c.argument('assign_endpoint', arg_type=get_three_state_flag(), help='If true, assign endpoint URL for direct access.') c.argument('scopes', arg_group='Single Sign On (SSO)', help="Comma-separated list of the specific actions applications can be allowed to do on a user's behalf.") c.argument('client_id', arg_group='Single Sign On (SSO)', help="The public identifier for the application.") @@ -854,19 +854,19 @@ def prepare_logs_argument(c): c.argument('metadata_url', arg_group='Single Sign On (SSO)', help="The URI of Issuer Identifier.") for scope in ['bind', 'unbind']: - with self.argument_context('spring service-registry {}'.format(scope)) as c: + with self.argument_context(f'spring service-registry {scope}') as c: c.argument('app', app_name_type, help='Name of app.', validator=validate_app_name) for scope in ['bind', 'unbind']: - with self.argument_context('spring application-configuration-service {}'.format(scope)) as c: + with self.argument_context(f'spring application-configuration-service {scope}') as c: c.argument('app', app_name_type, help='Name of app.', validator=validate_app_name) for scope in ['create', 'update']: - with self.argument_context('spring application-configuration-service {}'.format(scope)) as c: + with self.argument_context(f'spring application-configuration-service {scope}') as c: c.argument('generation', arg_type=get_enum_type(ConfigurationServiceGeneration), help='Generation of Application Configuration Service.') for scope in ['add', 'update']: - with self.argument_context('spring application-configuration-service git repo {}'.format(scope)) as c: + with self.argument_context(f'spring application-configuration-service git repo {scope}') as c: c.argument('patterns', help='Required patterns used to search in Git repositories. ' 'For each pattern, use format like {application} or {application}/{profile} ' @@ -884,15 +884,15 @@ def prepare_logs_argument(c): c.argument('ca_cert_name', help='CA certificate name.') for scope in ['add', 'update', 'remove']: - with self.argument_context('spring application-configuration-service git repo {}'.format(scope)) as c: + with self.argument_context(f'spring application-configuration-service git repo {scope}') as c: c.argument('name', help="Required unique name to label each item of git configs.") for scope in ['gateway create', 'api-portal create']: - with self.argument_context('spring {}'.format(scope)) as c: + with self.argument_context(f'spring {scope}') as c: c.argument('instance_count', type=int, help='Number of instance.') for scope in ['gateway update', 'api-portal update']: - with self.argument_context('spring {}'.format(scope)) as c: + with self.argument_context(f'spring {scope}') as c: c.argument('instance_count', type=int, help='Number of instance.') c.argument('assign_endpoint', arg_type=get_three_state_flag(), help='If true, assign endpoint URL for direct access.') c.argument('https_only', arg_type=get_three_state_flag(), help='If true, access endpoint via https') @@ -965,14 +965,14 @@ def prepare_logs_argument(c): 'gateway custom-domain update', 'api-portal custom-domain bind', 'api-portal custom-domain update']: - with self.argument_context('spring {}'.format(scope)) as c: + with self.argument_context(f'spring {scope}') as c: c.argument('certificate', type=str, help='Certificate name in Azure Spring Apps.') with self.argument_context('spring gateway route-config') as c: c.argument('name', help='Name of route config.') for scope in ['create', 'update']: - with self.argument_context('spring gateway route-config {}'.format(scope)) as c: + with self.argument_context(f'spring gateway route-config {scope}') as c: c.argument('app_name', type=str, help="The Azure Spring Apps app name to configure the route.") c.argument('routes_json', type=str, help="The JSON array of API routes.", validator=validate_routes) c.argument('routes_file', type=str, help="The file path of JSON array of API routes.", validator=validate_routes) diff --git a/src/spring/azext_spring/_stream_utils.py b/src/spring/azext_spring/_stream_utils.py index 34b88955a70..a9c8d7d4de7 100644 --- a/src/spring/azext_spring/_stream_utils.py +++ b/src/spring/azext_spring/_stream_utils.py @@ -31,7 +31,7 @@ def stream_logs(client, raise_error_on_failure=True, logger_level_func=logger.warning): log_file_sas = None - error_msg = "Could not get logs for Service: {}".format(service) + error_msg = f"Could not get logs for Service: {service}" try: log_file_sas = client.get_log_file_url( @@ -207,7 +207,7 @@ def safe_get_blob_properties(): logger_level_func(curr_bytes.decode('utf-8', errors='ignore')) build_status = _get_run_status(metadata).lower() - logger_level_func("Log status was: {}".format(build_status)) + logger_level_func(f"Log status was: {build_status}") if raise_error_on_failure: if build_status in ('internalerror', 'failed'): diff --git a/src/spring/azext_spring/_utils.py b/src/spring/azext_spring/_utils.py index c136c36e30b..88964d83bfe 100644 --- a/src/spring/azext_spring/_utils.py +++ b/src/spring/azext_spring/_utils.py @@ -38,7 +38,7 @@ def _get_upload_local_file(runtime_version, artifact_path=None, source_path=None file_type = "NetCoreZip" if runtime_version == SupportedRuntimeValue.NET_CORE31 else "Jar" elif source_path is not None: file_path = os.path.join(tempfile.gettempdir( - ), 'build_archive_{}.tar.gz'.format(uuid.uuid4().hex)) + ), f'build_archive_{uuid.uuid4().hex}.tar.gz') _pack_source_code(os.path.abspath(source_path), file_path) file_type = "Source" elif container_image is not None: @@ -178,7 +178,7 @@ def _archive_file_recursively(tar, name, arcname, parent_ignored, parent_matchin tarinfo = tar.gettarinfo(name, arcname) if tarinfo is None: - raise CLIError("tarfile: unsupported type {}".format(name)) + raise CLIError(f"tarfile: unsupported type {name}") # check if the file/dir is ignored ignored, matching_rule_index = ignore_check( @@ -220,7 +220,7 @@ def _get_azure_storage_client_info(account_type, sas_url): if not account_name or not container_name or not relative_path or not sas_token: raise CLIError( - "Failed to parse the SAS URL: '{!s}'.".format(sas_url)) + f"Failed to parse the SAS URL: '{sas_url}'.") return account_name, endpoint_suffix, container_name, relative_path, sas_token @@ -297,7 +297,7 @@ def convert_argument_to_parameter_list(args): def convert_argument_to_parameter(arg): - return '--{}'.format(arg.replace('_', '-')) + return f"--{arg.replace('_', '-')}" def wait_till_end(cmd, *pollers): diff --git a/src/spring/azext_spring/app.py b/src/spring/azext_spring/app.py index 9d0b0c4082f..a0c536a4276 100644 --- a/src/spring/azext_spring/app.py +++ b/src/spring/azext_spring/app.py @@ -171,11 +171,11 @@ def app_create(cmd, client, resource_group, service, name, banner_deployment_name = deployment_name or DEFAULT_DEPLOYMENT_NAME deployment_resource = deployment_factory.format_resource(**create_deployment_kwargs, **basic_kwargs) - logger.warning('[1/2] Creating app {}'.format(name)) + logger.warning(f'[1/2] Creating app {name}') app_poller = client.apps.begin_create_or_update(resource_group, service, name, app_resource) wait_till_end(cmd, app_poller) - logger.warning('[2/2] Creating default deployment with name "{}"'.format(banner_deployment_name)) + logger.warning(f'[2/2] Creating default deployment with name "{banner_deployment_name}"') poller = client.deployments.begin_create_or_update(resource_group, service, name, @@ -275,8 +275,7 @@ def app_update(cmd, client, resource_group, service, name, if deployment is None: updated_deployment_kwargs = {k: v for k, v in deployment_kwargs.items() if v} if updated_deployment_kwargs: - raise ArgumentUsageError('{} cannot be set when there is no active deployment.' - .format(convert_argument_to_parameter_list(updated_deployment_kwargs.keys()))) + raise ArgumentUsageError(f'{convert_argument_to_parameter_list(updated_deployment_kwargs.keys())} cannot be set when there is no active deployment.') deployment_factory = deployment_selector(**deployment_kwargs, **basic_kwargs) app_factory = app_selector(**basic_kwargs) @@ -408,10 +407,8 @@ def app_deploy(cmd, client, resource_group, service, name, deployment_factory = deployment_selector(**kwargs) kwargs.update(deployment_factory.get_fulfill_options(**kwargs)) deployment_resource = deployment_factory.format_resource(**kwargs) - logger.warning('[{}/{}] Updating deployment in app "{}" (this operation can take a ' - 'while to complete)'.format(kwargs['total_steps'], - kwargs['total_steps'], - name)) + logger.warning(f'[{kwargs["total_steps"]}/{kwargs["total_steps"]}] Updating deployment in app "{name}" (this operation can take a ' + f'while to complete)') poller = sdk_no_wait(no_wait, deployment_factory.get_deploy_method(**kwargs), resource_group, service, name, deployment.name, deployment_resource) @@ -472,8 +469,8 @@ def _print_deploy_process(client, poller, resource_group, service, app_name, dep else: instance_desc = str(instance_count) + " instance" rounds_desc = str(rounds) + " round" - logger.warning('Azure Spring Apps will use rolling upgrade to update your deployment, you have {}, ' - 'Azure Spring Apps will update the deployment in {}.'.format(instance_desc, rounds_desc)) + logger.warning(f'Azure Spring Apps will use rolling upgrade to update your deployment, you have {instance_desc}, ' + f'Azure Spring Apps will update the deployment in {rounds_desc}.') last_round = 0 deployment_time = deployment_resource.system_data.last_modified_at.strftime("%Y-%m-%dT%H:%M:%S%z") @@ -490,16 +487,16 @@ def _print_deploy_process(client, poller, resource_group, service, app_name, dep current_round = new_instance_count // instance_round + (0 if new_instance_count % instance_round == 0 else 1) if current_round != last_round: if int(current_round) > 1: - old_desc = "{} old instances are".format(int(new_instance_count)) + old_desc = f"{int(new_instance_count)} old instances are" else: - old_desc = "{} old instance is".format(int(new_instance_count)) + old_desc = f"{int(new_instance_count)} old instance is" if int(new_instance_count) > 1: - new_desc = "{} new instances are".format(int(new_instance_count)) + new_desc = f"{int(new_instance_count)} new instances are" else: - new_desc = "{} new instance is".format(int(new_instance_count)) + new_desc = f"{int(new_instance_count)} new instance is" logger.warning( - 'The deployment is in round {}, {} deleted/deleting and {} ' - 'started/starting'.format(int(current_round), old_desc, new_desc)) + f'The deployment is in round {int(current_round)}, {old_desc} deleted/deleting and {new_desc} ' + f'started/starting') last_round = current_round sleep(5) logger.warning("Your application is successfully deployed.") @@ -638,10 +635,8 @@ def deployment_create(cmd, client, resource_group, service, app, name, kwargs['deployable_path'] = deploy.build_deployable_path(**kwargs) deployment_factory = deployment_selector(**kwargs) deployment_resource = deployment_factory.format_resource(**kwargs) - logger.warning('[{}/{}] Creating deployment in app "{}" (this operation can take a ' - 'while to complete)'.format(kwargs['total_steps'], - kwargs['total_steps'], - app)) + logger.warning(f'[{kwargs["total_steps"]}/{kwargs["total_steps"]}] Creating deployment in app "{app}" (this operation can take a ' + f'while to complete)') poller = sdk_no_wait(no_wait, client.deployments.begin_create_or_update, resource_group, service, app, name, deployment_resource) @@ -660,7 +655,7 @@ def _ensure_app_not_exist(client, resource_group, service, name): # ignore return if app: - raise ValidationError('App {} already exist.'.format(app.id)) + raise ValidationError(f'App {app.id} already exist.') def _fulfill_deployment_creation_options(skip_clone_settings, client, resource_group, service, app, **kwargs): diff --git a/src/spring/azext_spring/application_accelerator.py b/src/spring/azext_spring/application_accelerator.py index c958560c315..563d675e2a5 100644 --- a/src/spring/azext_spring/application_accelerator.py +++ b/src/spring/azext_spring/application_accelerator.py @@ -51,10 +51,9 @@ def application_accelerator_delete(cmd, client, resource_group, service, no_wait def _get_enable_dev_tool_portal_poller(cmd, client, service, resource_group): dev_tool_portal = get_dev_tool_portal(cmd, client, service, resource_group) if not dev_tool_portal: - logger.warning('- View Application Accelerator through Dev Tool portal. ' - 'Create Dev Tool Portal by running ' - '"az spring dev-tool create --service {} --resource-group {} --assign-endpoint"' - .format(service, resource_group)) + logger.warning(f'- View Application Accelerator through Dev Tool portal. ' + f'Create Dev Tool Portal by running ' + f'"az spring dev-tool create --service {service} --resource-group {resource_group} --assign-endpoint"') return None if not is_dev_tool_portal_updatable(dev_tool_portal): return None diff --git a/src/spring/azext_spring/custom.py b/src/spring/azext_spring/custom.py index 36e71b84c59..6ae86b0abf2 100644 --- a/src/spring/azext_spring/custom.py +++ b/src/spring/azext_spring/custom.py @@ -1112,7 +1112,7 @@ def binding_redis_add(cmd, client, resource_group, service, app, name, primary_key = _get_redis_primary_key(cmd.cli_ctx, resource_id) except: raise CLIError( - "Couldn't get redis {}'s primary key".format(resource_name)) + f"Couldn't get redis {resource_name}'s primary key") properties = models.BindingResourceProperties( resource_name=resource_name, @@ -1138,7 +1138,7 @@ def binding_redis_update(cmd, client, resource_group, service, app, name, primary_key = _get_redis_primary_key(cmd.cli_ctx, resource_id) except: raise CLIError( - "Couldn't get redis {}'s primary key".format(resource_name)) + f"Couldn't get redis {resource_name}'s primary key") properties = models.BindingResourceProperties( key=primary_key, @@ -1227,7 +1227,7 @@ def format_line(line): except: if first_exception: # enable this format error logging only with --verbose - logger.info("Failed to format log line '{}'".format(line), exc_info=sys.exc_info()) + logger.info(f"Failed to format log line '{line}'", exc_info=sys.exc_info()) first_exception = False return line @@ -1272,11 +1272,10 @@ def iter_lines(response, limit=2 ** 20, chunk_size=None): failure_reason = response.reason if response.content: if isinstance(response.content, bytes): - failure_reason = "{}:{}".format(failure_reason, response.content.decode('utf-8')) + failure_reason = f"{failure_reason}:{response.content.decode('utf-8')}" else: - failure_reason = "{}:{}".format(failure_reason, response.content) - raise CLIError("Failed to connect to the server with status code '{}' and reason '{}'".format( - response.status_code, failure_reason)) + failure_reason = f"{failure_reason}:{response.content}" + raise CLIError(f"Failed to connect to the server with status code '{response.status_code}' and reason '{failure_reason}'") std_encoding = sys.stdout.encoding formatter = build_formatter() @@ -1384,9 +1383,9 @@ def certificate_add(cmd, client, resource_group, service, name, only_public_cert logger.debug("attempting to read file %s as binary", public_certificate_file) content = base64.b64encode(input_file.read()).decode("utf-8") except Exception: - raise FileOperationError('Failed to decode file {} - unknown decoding'.format(public_certificate_file)) + raise FileOperationError(f'Failed to decode file {public_certificate_file} - unknown decoding') else: - raise FileOperationError("public_certificate_file {} could not be found".format(public_certificate_file)) + raise FileOperationError(f"public_certificate_file {public_certificate_file} could not be found") properties = models.ContentCertificateProperties( type="ContentCertificate", content=content @@ -1477,7 +1476,7 @@ def _update_app_e2e_tls(cmd, client, resource_group, service, app, enable_ingres app_resource.properties = properties app_resource.location = location - logger.warning("Set ingress to app tls for app '{}'".format(app)) + logger.warning(f"Set ingress to app tls for app '{app}'") poller = client.apps.begin_update( resource_group, service, app, app_resource) return poller.result() @@ -1519,8 +1518,7 @@ def get_app_insights_connection_string(cli_ctx, resource_group, name): appinsights_client = get_mgmt_service_client(cli_ctx, ApplicationInsightsManagementClient) appinsights = appinsights_client.components.get(resource_group, name) if appinsights is None or appinsights.connection_string is None: - raise ResourceNotFoundError("App Insights {} under resource group {} was not found." - .format(name, resource_group)) + raise ResourceNotFoundError(f"App Insights {name} under resource group {resource_group} was not found.") return appinsights.connection_string @@ -1580,7 +1578,7 @@ def _get_connection_string_from_app_insights(cmd, resource_group, app_insights): connection_string = get_app_insights_connection_string(cmd.cli_ctx, resource_group, app_insights) if not connection_string: raise InvalidArgumentValueError( - "Cannot find Connection string from application insights:{}".format(app_insights)) + f"Cannot find Connection string from application insights:{app_insights}") return connection_string @@ -1677,13 +1675,12 @@ def app_connect(cmd, client, resource_group, service, name, resource = client.services.get(resource_group, service) if not instance: if not deployment.properties.instances: - raise ResourceNotFoundError("No instances found for deployment '{0}' in app '{1}'".format( - deployment.name, name)) + raise ResourceNotFoundError(f"No instances found for deployment '{deployment.name}' in app '{name}'") instances = deployment.properties.instances if len(instances) > 1: logger.warning("Multiple app instances found:") for temp_instance in instances: - logger.warning("{}".format(temp_instance.name)) + logger.warning(f"{temp_instance.name}") logger.warning("Please use '-i/--instance' parameter to specify the instance name") return None instance = instances[0].name @@ -1691,13 +1688,12 @@ def app_connect(cmd, client, resource_group, service, name, if resource.sku.tier.upper() == 'STANDARDGEN2': subscriptionId = get_subscription_id(cmd.cli_ctx) hostname = get_proxy_api_endpoint(cmd.cli_ctx, resource) - connect_url = "wss://{}/proxy/appconnect/subscriptions/{}/resourceGroups/{}/providers/Microsoft.AppPlatform/Spring/{}/apps/{}/deployments/{}/instances/{}?tenantId={}&command={}".format( - hostname, subscriptionId, resource_group, resource.name, name, deployment.name, instance, tenant, shell_cmd) + connect_url = f"wss://{hostname}/proxy/appconnect/subscriptions/{subscriptionId}/resourceGroups/{resource_group}/providers/Microsoft.AppPlatform/Spring/{resource.name}/apps/{name}/deployments/{deployment.name}/instances/{instance}?tenantId={tenant}&command={shell_cmd}" logger.warning("Connecting to %s...", connect_url) else: hostname = resource.properties.fqdn - connect_url = "wss://{0}/api/appconnect/apps/{1}/deployments/{2}/instances/{3}/connect?command={4}".format(hostname, name, deployment.name, instance, shell_cmd) - logger.warning("Connecting to the app instance Microsoft.AppPlatform/Spring/%s/apps/%s/deployments/%s/instances/%s..." % (service, name, deployment.name, instance)) + connect_url = f"wss://{hostname}/api/appconnect/apps/{name}/deployments/{deployment.name}/instances/{instance}/connect?command={shell_cmd}" + logger.warning(f"Connecting to the app instance Microsoft.AppPlatform/Spring/{service}/apps/{name}/deployments/{deployment.name}/instances/{instance}...") conn = WebSocketConnection(connect_url, token) diff --git a/src/spring/azext_spring/service_registry.py b/src/spring/azext_spring/service_registry.py index 4390809f212..ff317279147 100644 --- a/src/spring/azext_spring/service_registry.py +++ b/src/spring/azext_spring/service_registry.py @@ -42,7 +42,7 @@ def _service_registry_bind_or_unbind_app(cmd, client, service, resource_group, a app.properties.addon_configs = _get_app_addon_configs_with_service_registry(app.properties.addon_configs) if (app.properties.addon_configs[SERVICE_REGISTRY_NAME][RESOURCE_ID] != "") == enabled: - logger.warning('App "{}" has been {}binded'.format(app_name, '' if enabled else 'un')) + logger.warning(f'App "{app_name}" has been {"" if enabled else "un"}binded') return app service_registry_id = resource_id(