Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix quantum lint #7152

Merged
merged 9 commits into from
Jan 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/quantum/azext_quantum/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

# pylint: disable=line-too-long

from azure.cli.core import AzCommandsLoader

import azext_quantum._help # pylint: disable=unused-import
Expand Down Expand Up @@ -35,7 +37,7 @@ def load_arguments(self, command):
from ._version_check_helper import check_version
from .operations.workspace import _show_tip
from datetime import datetime
message = check_version(self.cli_ctx_config, CLI_REPORTED_VERSION, str(datetime.today()).split(' ')[0])
message = check_version(self.cli_ctx_config, CLI_REPORTED_VERSION, str(datetime.today()).split(' ', maxsplit=1)[0])
if message is not None:
_show_tip(message)

Expand Down
6 changes: 3 additions & 3 deletions src/quantum/azext_quantum/_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

# pylint: disable=line-too-long,protected-access,no-self-use,too-many-statements
# pylint: disable=line-too-long,protected-access,too-many-statements

import argparse
from knack.arguments import CLIArgumentType
Expand All @@ -27,11 +27,11 @@ def get_action(self, values, option_string):
key, value = item.split('=', 1)
params[key] = value
except ValueError as e:
raise InvalidArgumentValueError('Usage error: {} KEY=VALUE [KEY=VALUE ...], json string, or @file expected'.format(option_string)) from e
raise InvalidArgumentValueError(f'Usage error: {option_string} KEY=VALUE [KEY=VALUE ...], json string, or @file expected') from e
return params


def load_arguments(self, _):
def load_arguments(self, _): # pylint: disable=too-many-locals
workspace_name_type = CLIArgumentType(options_list=['--workspace-name', '-w'], help='Name of the Quantum Workspace. You can configure the default workspace using `az quantum workspace set`.', configured_default='workspace', id_part=None)
storage_account_name_type = CLIArgumentType(options_list=['--storage-account', '-a'], help='Name of the storage account to be used by a quantum workspace.')
program_args_type = CLIArgumentType(nargs='*', help='List of arguments expected by the Q# operation specified as --name=value after `--`.')
Expand Down
8 changes: 4 additions & 4 deletions src/quantum/azext_quantum/_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ def create_container_using_client(container_client: ContainerClient):
"""
if not container_client.exists():
logger.debug(
f'{" - uploading to **new** container:"}'
f"{container_client.container_name}"
" - uploading to **new** container: %s",
container_client.container_name
)
container_client.create_container()

Expand Down Expand Up @@ -82,13 +82,13 @@ def upload_blob(
blob = container.get_blob_client(blob_name)

blob.upload_blob(data, content_settings=content_settings)
logger.debug(f" - blob '{blob_name}' uploaded. generating sas token.")
logger.debug(" - blob '%s' uploaded. generating sas token.", blob_name)

if return_sas_token:
uri = get_blob_uri_with_sas_token(blob)
else:
uri = remove_sas_token(blob.url)
logger.debug(f" - blob access url: '{uri}'.")
logger.debug(" - blob access url: '%s'.", uri)

return uri

Expand Down
2 changes: 1 addition & 1 deletion src/quantum/azext_quantum/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def one(key, value):
]))
return table

elif isinstance(results, list) and len(results) > 0 and 'reportData' in results[0]:
elif isinstance(results, list) and len(results) > 0 and 'reportData' in results[0]: # pylint: disable=too-many-nested-blocks
table = []

indices = range(len(results))
Expand Down
13 changes: 7 additions & 6 deletions src/quantum/azext_quantum/operations/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@

_targets_with_allowed_failure_output = {"microsoft.dft"}


def _show_warning(msg):
import colorama
colorama.init()
Expand Down Expand Up @@ -269,7 +270,7 @@ def _submit_directly_to_service(cmd, resource_group_name, workspace_name, locati
raise RequiredArgumentMissingError(ERROR_MSG_MISSING_OUTPUT_FORMAT, JOB_SUBMIT_DOC_LINK_MSG)

# An entry point is required on QIR jobs
if job_type == QIR_JOB:
if job_type == QIR_JOB: # pylint: disable=too-many-nested-blocks
# An entry point is required for a QIR job, but there are four ways to specify it in a CLI command:
# - Use the --entry-point parameter
# - Include it in --job-params as entryPoint=MyEntryPoint
Expand Down Expand Up @@ -413,8 +414,8 @@ def _submit_directly_to_service(cmd, resource_group_name, workspace_name, locati
if shots is not None:
try:
job_params["shots"] = int(shots)
except:
raise InvalidArgumentValueError("Invalid --shots value. Shots must be an integer.")
except Exception as exc:
raise InvalidArgumentValueError("Invalid --shots value. Shots must be an integer.") from exc
if target_capability is not None:
job_params["targetCapability"] = target_capability
if entry_point is not None:
Expand All @@ -424,8 +425,8 @@ def _submit_directly_to_service(cmd, resource_group_name, workspace_name, locati
if "count" in job_params.keys():
try:
job_params["count"] = int(job_params["count"])
except:
raise InvalidArgumentValueError("Invalid count value. Count must be an integer.")
except Exception as exc:
raise InvalidArgumentValueError("Invalid count value. Count must be an integer.") from exc

# Convert all other numeric parameter values from string to int or float
_convert_numeric_params(job_params)
Expand Down Expand Up @@ -663,7 +664,7 @@ def _get_job_output(cmd, job, item=None):

blob_service.get_blob_to_path(containerName, blobName, path)

with open(path) as json_file:
with open(path, encoding="utf-8") as json_file:
lines = [line.strip() for line in json_file.readlines()]

# Receiving an empty response is valid.
Expand Down
8 changes: 3 additions & 5 deletions src/quantum/azext_quantum/operations/workspace.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def _add_quantum_providers(cmd, workspace, providers, auto_accept, skip_autoadd)
_autoadd_providers(cmd, providers_in_region, providers_selected, workspace.location, auto_accept)

# If there weren't any autoAdd providers and none were specified with the -r parameter, we have a problem...
if providers_selected == []:
if not providers_selected:
raise RequiredArgumentMissingError("A list of Azure Quantum providers and SKUs (plans) is required.",
"Supply the missing -r parameter. For example:\n"
"\t-r \"Microsoft/Basic, Microsoft.FleetManagement/Basic\"\n"
Expand Down Expand Up @@ -202,12 +202,10 @@ def _create_role_assignment(cmd, quantum_workspace):

def _validate_storage_account(tier_or_kind_msg_text, tier_or_kind, supported_tiers_or_kinds):
if tier_or_kind not in supported_tiers_or_kinds:
tier_or_kind_list = ''
for item in supported_tiers_or_kinds:
tier_or_kind_list += f"{item}, "
tier_or_kind_list = ', '.join(supported_tiers_or_kinds)
plural = 's' if len(supported_tiers_or_kinds) != 1 else ''
raise InvalidArgumentValueError(f"Storage account {tier_or_kind_msg_text} '{tier_or_kind}' is not supported.\n"
f"Storage account {tier_or_kind_msg_text}{plural} currently supported: {tier_or_kind_list[:-2]}")
f"Storage account {tier_or_kind_msg_text}{plural} currently supported: {tier_or_kind_list}")


def create(cmd, resource_group_name, workspace_name, location, storage_account, skip_role_assignment=False,
Expand Down
118 changes: 59 additions & 59 deletions src/quantum/azext_quantum/tests/latest/test_quantum_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from azure.cli.testsdk import ScenarioTest
from azure.cli.core.azclierror import InvalidArgumentValueError, AzureInternalError

from .utils import get_test_subscription_id, get_test_resource_group, get_test_workspace, get_test_workspace_location, issue_cmd_with_param_missing, get_test_workspace_storage, get_test_workspace_random_name
from .utils import get_test_subscription_id, get_test_resource_group, get_test_workspace, get_test_workspace_location, get_test_workspace_location_for_dft, issue_cmd_with_param_missing, get_test_workspace_storage, get_test_workspace_random_name
from ..._client_factory import _get_data_credentials
from ...commands import transform_output
from ...operations.workspace import WorkspaceInfo, DEPLOYMENT_NAME_PREFIX
Expand Down Expand Up @@ -126,7 +126,7 @@ def test_transform_output(self):
table_row = table[0]
hist_row = table_row['']
second_char = hist_row[1]
self.assertEquals(second_char, "\u2588") # Expecting a "Full Block" character here
self.assertEquals(second_char, "\u2588") # Expecting a "Full Block" character here

# Give it a malformed histogram
test_job_results = '{"Histogram":["[0,0,0]",0.125,"[1,0,0]",0.125,"[0,1,0]",0.125,"[1,1,0]"]}'
Expand All @@ -135,36 +135,36 @@ def test_transform_output(self):

# Call with output from a failed job
test_job_results = \
'{\
"beginExecutionTime": "2022-02-25T18:57:26.093000+00:00",\
"cancellationTime": null,\
"containerUri": "https://foo...",\
"costEstimate": null,\
"creationTime": "2022-02-25T18:56:53.275035+00:00",\
"endExecutionTime": "2022-02-25T18:57:26.093000+00:00",\
"errorData": {\
"code": "InsufficientResources",\
"message": "Too many qubits requested"\
},\
"id": "11111111-2222-3333-4444-555555555555",\
"inputDataFormat": "microsoft.ionq-ir.v2",\
"inputDataUri": "https://bar...",\
"inputParams": {\
"shots": "500"\
},\
"isCancelling": false,\
"metadata": {\
"entryPointInput": {\"Qubits\":null},\
"outputMappingBlobUri": "https://baz..."\
},\
"name": "",\
"outputDataFormat": "microsoft.quantum-results.v1",\
"outputDataUri": "https://quux...",\
"providerId": "ionq",\
"status": "Failed",\
"tags": [],\
"target": "ionq.simulator"\
}'
'{\
"beginExecutionTime": "2022-02-25T18:57:26.093000+00:00",\
"cancellationTime": null,\
"containerUri": "https://foo...",\
"costEstimate": null,\
"creationTime": "2022-02-25T18:56:53.275035+00:00",\
"endExecutionTime": "2022-02-25T18:57:26.093000+00:00",\
"errorData": {\
"code": "InsufficientResources",\
"message": "Too many qubits requested"\
},\
"id": "11111111-2222-3333-4444-555555555555",\
"inputDataFormat": "microsoft.ionq-ir.v2",\
"inputDataUri": "https://bar...",\
"inputParams": {\
"shots": "500"\
},\
"isCancelling": false,\
"metadata": {\
"entryPointInput": {\"Qubits\":null},\
"outputMappingBlobUri": "https://baz..."\
},\
"name": "",\
"outputDataFormat": "microsoft.quantum-results.v1",\
"outputDataUri": "https://quux...",\
"providerId": "ionq",\
"status": "Failed",\
"tags": [],\
"target": "ionq.simulator"\
}'

table = transform_output(json.loads(test_job_results))
self.assertEquals(table['Status'], "Failed")
Expand All @@ -176,30 +176,30 @@ def test_transform_output(self):

# Call with missing "status", "code", "message", "target", "id", and "creationTime"
test_job_results = \
'{\
"beginExecutionTime": "2022-02-25T18:57:26.093000+00:00",\
"cancellationTime": null,\
"containerUri": "https://foo...",\
"costEstimate": null,\
"endExecutionTime": "2022-02-25T18:57:26.093000+00:00",\
"errorData": {\
},\
"inputDataFormat": "microsoft.ionq-ir.v2",\
"inputDataUri": "https://bar...",\
"inputParams": {\
"shots": "500"\
},\
"isCancelling": false,\
"metadata": {\
"entryPointInput": {\"Qubits\":null},\
"outputMappingBlobUri": "https://baz..."\
},\
"name": "",\
"outputDataFormat": "microsoft.quantum-results.v1",\
"outputDataUri": "https://quux...",\
"providerId": "ionq",\
"tags": []\
}'
'{\
"beginExecutionTime": "2022-02-25T18:57:26.093000+00:00",\
"cancellationTime": null,\
"containerUri": "https://foo...",\
"costEstimate": null,\
"endExecutionTime": "2022-02-25T18:57:26.093000+00:00",\
"errorData": {\
},\
"inputDataFormat": "microsoft.ionq-ir.v2",\
"inputDataUri": "https://bar...",\
"inputParams": {\
"shots": "500"\
},\
"isCancelling": false,\
"metadata": {\
"entryPointInput": {\"Qubits\":null},\
"outputMappingBlobUri": "https://baz..."\
},\
"name": "",\
"outputDataFormat": "microsoft.quantum-results.v1",\
"outputDataUri": "https://quux...",\
"providerId": "ionq",\
"tags": []\
}'

table = transform_output(json.loads(test_job_results))
notFound = "Not found"
Expand Down Expand Up @@ -282,7 +282,7 @@ def test_submit(self):

@live_only()
def test_submit_dft(self):
test_location = "westus" # DFT is not enabled in WestUS2
test_location = get_test_workspace_location_for_dft()
test_resource_group = get_test_resource_group()
test_workspace_temp = get_test_workspace_random_name()
test_provider_sku_list = "microsoft-elements/elements-internal-testing"
Expand All @@ -291,7 +291,7 @@ def test_submit_dft(self):
self.cmd(f"az quantum workspace create -g {test_resource_group} -w {test_workspace_temp} -l {test_location} -a {test_storage} -r \"{test_provider_sku_list}\" --skip-autoadd")
self.cmd(f"az quantum workspace set -g {test_resource_group} -w {test_workspace_temp} -l {test_location}")

# Run a "microsoft.dft" job to test that successful job returns proper output
# Run a "microsoft.dft" job to test that successful job returns proper output
results = self.cmd("az quantum run -t microsoft.dft --job-input-format microsoft.xyz.v1 --job-output-format microsoft.dft-results.v1 --job-input-file src/quantum/azext_quantum/tests/latest/input_data/dft_molecule_success.xyz --job-params {{\\\"tasks\\\":[{{\\\"taskType\\\":\\\"spe\\\",\\\"basisSet\\\":{{\\\"name\\\":\\\"def2-svp\\\",\\\"cartesian\\\":false}},\\\"xcFunctional\\\":{{\\\"name\\\":\\\"m06-2x\\\",\\\"gridLevel\\\":4}},\\\"scf\\\":{{\\\"method\\\":\\\"rks\\\",\\\"maxSteps\\\":100,\\\"convergeThreshold\\\":1e-8}}}}]}} -o json").get_output_in_json()
self.assertIsNotNone(results["results"])
self.assertTrue(len(results["results"]) == 1)
Expand All @@ -314,4 +314,4 @@ def test_submit_dft(self):
self.assertTrue(len(results["results"]) == 1)
self.assertFalse(results["results"][0]["success"])

self.cmd(f'az quantum workspace delete -g {test_resource_group} -w {test_workspace_temp}')
self.cmd(f'az quantum workspace delete -g {test_resource_group} -w {test_workspace_temp}')
12 changes: 6 additions & 6 deletions src/quantum/azext_quantum/tests/latest/test_quantum_targets.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,32 +25,32 @@ def test_targets(self):
self.cmd(f'az quantum workspace set -g {get_test_resource_group()} -w {get_test_workspace()} -l {get_test_workspace_location()}')

# clear current target
self.cmd(f'az quantum target clear')
self.cmd('az quantum target clear')

# list
targets = self.cmd('az quantum target list -o json').get_output_in_json()
assert len(targets) > 0

# set
self.cmd(f'az quantum target set -t microsoft.estimator -o json', checks=[
self.cmd('az quantum target set -t microsoft.estimator -o json', checks=[
self.check("targetId", "microsoft.estimator")
])

# show
self.cmd(f'az quantum target show -o json', checks=[
self.cmd('az quantum target show -o json', checks=[
self.check("targetId", "microsoft.estimator")
])

# clear
self.cmd(f'az quantum target clear')
self.cmd('az quantum target clear')

# show
self.cmd(f'az quantum target show -t microsoft.estimator -o json', checks=[
self.cmd('az quantum target show -t microsoft.estimator -o json', checks=[
self.check("targetId", "microsoft.estimator")
])

def test_target_errors(self):
self.cmd(f'az quantum target clear')
self.cmd('az quantum target clear')
issue_cmd_with_param_missing(self, "az quantum target set", "az quantum target set -t target-id\nSelect a default when submitting jobs to Azure Quantum.")

@live_only()
Expand Down
Loading