From cedf43e90ee57db88a468d5627c8e41616bbfad8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milan=20P=C3=A1nik?= Date: Wed, 2 Dec 2026 08:56:08 -0500 Subject: [PATCH 1/3] [CU-1k5fpdaa5gp] Add workbench runs orchestrate: the server groups samples into runs Co-Authored-By: Claude Sonnet 5.5 --- .../cli/commands/workbench/runs/commands.py | 145 +++++++++++++++++- dnastack/client/workbench/ewes/client.py | 9 +- dnastack/client/workbench/ewes/models.py | 28 ++++ .../unit/cli/workbench/test_runs_commands.py | 130 +++++++++++++++- .../client/workbench/ewes/test_ewes_client.py | 35 ++++- 5 files changed, 343 insertions(+), 4 deletions(-) diff --git a/dnastack/cli/commands/workbench/runs/commands.py b/dnastack/cli/commands/workbench/runs/commands.py index 44ff757d..d9f222de 100644 --- a/dnastack/cli/commands/workbench/runs/commands.py +++ b/dnastack/cli/commands/workbench/runs/commands.py @@ -16,13 +16,39 @@ from dnastack.cli.helpers.iterator_printer import show_iterator, OutputFormat from dnastack.client.workbench.ewes.models import ExtendedRunListOptions, ExtendedRunRequest, \ BatchRunRequest, \ - MinimalExtendedRunWithOutputs, MinimalExtendedRunWithInputs, ExecutionEngineListOptions, SimpleSample + MinimalExtendedRunWithOutputs, MinimalExtendedRunWithInputs, ExecutionEngineListOptions, SimpleSample, \ + OrchestrationRequest, OrchestrationRunRequestTemplate, EngineParamPresetListOptions +from dnastack.client.workbench.ewes.client import EWesClient from dnastack.client.workbench.common.models import State from dnastack.client.workbench.ewes.models import LogType from dnastack.common.json_argument_parser import JsonLike, parse_and_merge_arguments, merge, merge_param_json_data from dnastack.common.tracing import Span +def _get_default_engine_id(ewes_client: EWesClient) -> str: + for engine in ewes_client.list_engines(ExecutionEngineListOptions()): + if engine.default: + return engine.id + raise NoDefaultEngineError("No default engine found. Please specify an engine id using the --engine flag.") + + +def _resolve_engine_parameters(ewes_client: EWesClient, engine_id: str, engine_params: Optional[JsonLike]) -> dict: + if not engine_params: + default_preset = next((preset for preset in + ewes_client.list_engine_param_presets(engine_id, EngineParamPresetListOptions()) + if preset.default), None) + return {'engine_id': engine_id, **(default_preset.preset_values if default_preset else {})} + + [param_ids_list, kv_pairs_list, json_literals_list, files_list] = engine_params.extract_arguments_list() + resolved = merge_param_json_data(kv_pairs_list, json_literals_list, files_list) + for param_id in param_ids_list or []: + try: + merge(resolved, ewes_client.get_engine_param_preset(engine_id, param_id).preset_values) + except Exception as e: + raise UnableToFindParameterError(f"Unable to find engine parameter preset with id {param_id}. {e}") + return resolved + + def init_runs_commands(group: Group): @formatted_command( group=group, @@ -660,3 +686,120 @@ def get_default_engine_id(): else: minimal_batch = ewes_client.submit_batch(batch_request) click.echo(to_json(normalize(minimal_batch))) + + @formatted_command( + group=group, + name='orchestrate', + specs=[ + ArgumentSpec( + name='workflow', + arg_names=['--workflow'], + help='The id of the workflow to run.', + required=True, + ), + ArgumentSpec( + name='version', + arg_names=['--version'], + help='The version of the workflow to run.', + required=True, + ), + ArgumentSpec( + name='samples', + arg_names=['--sample'], + help='The ID of a sample to run the workflow on. Can be specified multiple times. ' + 'The server decides how the samples are grouped into runs.', + multiple=True, + ), + ArgumentSpec( + name='storage_account_id', + arg_names=['--storage-account'], + help='The storage account ID that the samples belong to. ' + STORAGE_ACCOUNT_DEFAULT_HELP, + ), + ArgumentSpec( + name='engine_id', + arg_names=['--engine'], + help='Use the given engine id for execution of runs. If this value is not defined then the ' + 'default engine will be used.', + ), + ArgumentSpec( + name='engine_params', + arg_names=['--engine-params'], + help='Set the engine parameters for all runs. ' + 'Engine params can be specified as inlined JSON, json file preceded by the "@" symbol, ' + 'KV pair, parameter preset ID, or as a comma-separated-list containing any of those types ' + '(e.g. my-preset-id,key=value,\'{"literal":"json"}\',@file.json). ' + 'If not specified, the default parameter preset of the engine is used.', + type=JsonLike, + ), + ArgumentSpec( + name='tags', + help='Set the tags for all runs. ' + 'Tags can be any JSON-like value, such as inline JSON, command separated key value pairs or ' + 'a json file referenced preceded by the "@" symbol.', + type=JsonLike, + ), + ArgumentSpec( + name='dry_run', + arg_names=['--dry-run'], + help='Ask the server how the samples would be grouped into runs, and print that plan. ' + 'No runs are created. This differs from "runs submit --dry-run", which only prints ' + 'the request and calls nothing.', + type=bool, + ), + ArgumentSpec( + name='no_ingest_variants', + arg_names=['--no-ingest-variants'], + help='Do not run the variant ingestion step. Without this flag the server decides: it ingests ' + 'variants when the workflow is labelled "tertiary". This applies to the workflow named ' + 'here, not to the prerequisite workflows the server adds.', + type=bool, + ), + NAMESPACE_ARG, + CONTEXT_ARG, + SINGLE_ENDPOINT_ID_ARG, + ] + ) + def orchestrate(context: Optional[str], + endpoint_id: Optional[str], + namespace: Optional[str], + workflow: str, + version: str, + samples: List[str], + storage_account_id: Optional[str], + engine_id: Optional[str], + engine_params: Optional[JsonLike], + tags: Optional[JsonLike], + dry_run: bool, + no_ingest_variants: bool): + """ + Create runs of a workflow from samples, grouped by the server + + The server decides how the samples are grouped into runs, as Workbench does when you select samples. + """ + if not samples: + raise click.UsageError('You must specify at least one --sample.') + + ewes_client = get_ewes_client(context_name=context, endpoint_id=endpoint_id, namespace=namespace) + storage_account_id = resolve_storage_account_id(storage_account_id, + context_name=context, + namespace=ewes_client.namespace) + engine_id = engine_id or _get_default_engine_id(ewes_client) + + template_fields = {'ingest_variants': False} if no_ingest_variants else {} + request = OrchestrationRequest( + samples=[SimpleSample(id=sample_id, storage_account_id=storage_account_id) for sample_id in samples], + request_templates=[OrchestrationRunRequestTemplate( + workflow_id=workflow, + workflow_version_id=version, + workflow_url=f'{workflow}/{version}', + workflow_type='WDL', + engine_id=engine_id, + default_workflow_engine_parameters=_resolve_engine_parameters(ewes_client, engine_id, engine_params), + **template_fields, + )], + engine_id=engine_id, + tags=tags.parsed_value() if tags else None, + dry_run=bool(dry_run), + ) + + click.echo(to_json(normalize(ewes_client.orchestrate(request)))) diff --git a/dnastack/client/workbench/ewes/client.py b/dnastack/client/workbench/ewes/client.py index a7bea22d..987b1854 100644 --- a/dnastack/client/workbench/ewes/client.py +++ b/dnastack/client/workbench/ewes/client.py @@ -11,7 +11,7 @@ from dnastack.client.workbench.ewes.models import ExtendedRunEvents, WesServiceInfo, ExtendedRunStatus, \ ExtendedRunListOptions, \ ExtendedRunListResponse, ExtendedRun, RunId, WorkbenchApiError, BatchActionResult, MinimalExtendedRun, \ - BatchRunResponse, BatchRunRequest, ExtendedRunRequest, Log, TaskListOptions, \ + BatchRunResponse, BatchRunRequest, ExtendedRunRequest, OrchestrationRequest, OrchestrationRunsResponse, Log, TaskListOptions, \ TaskListResponse, LogType, ExecutionEngineListOptions, ExecutionEngineListResponse, ExecutionEngine, \ EngineParamPreset, EngineParamPresetListOptions, EngineParamPresetListResponse, \ EngineHealthCheck, EngineHealthCheckListOptions, EngineHealthCheckListResponse, \ @@ -234,6 +234,13 @@ def submit_batch(self, data: BatchRunRequest, trace: Optional[Span] = None) -> B trace_context=trace) return BatchRunResponse(**response.json()) + def orchestrate(self, data: OrchestrationRequest, trace: Optional[Span] = None) -> OrchestrationRunsResponse: + with self.create_http_session() as session: + response = session.post(urljoin(self.endpoint.url, f'{self.namespace}/ga4gh/wes/v1/runs/orchestrate'), + json=data.model_dump(exclude_unset=True), + trace_context=trace) + return OrchestrationRunsResponse(**response.json()) + def stream_run_logs(self, run_id: str, log_type: LogType = LogType.STDOUT, diff --git a/dnastack/client/workbench/ewes/models.py b/dnastack/client/workbench/ewes/models.py index e00f1601..ddef46ee 100644 --- a/dnastack/client/workbench/ewes/models.py +++ b/dnastack/client/workbench/ewes/models.py @@ -310,6 +310,34 @@ class BatchRunResponse(BaseModel): runs: List[MinimalExtendedRun] +class OrchestrationRunRequestTemplate(BaseModel): + workflow_id: str + workflow_version_id: str + workflow_url: str + workflow_type: str + engine_id: Optional[str] = None + default_workflow_engine_parameters: Optional[Dict] = None + ingest_variants: Optional[bool] = None + + +class OrchestrationRequest(BaseModel): + samples: List[SimpleSample] + request_templates: List[OrchestrationRunRequestTemplate] + engine_id: Optional[str] = None + tags: Optional[Dict] = None + dry_run: bool = False + + +class OrchestrationRun(BaseModel): + samples: List[SimpleSample] + runs: List[Dict] + + +class OrchestrationRunsResponse(BaseModel): + orchestration_runs: List[OrchestrationRun] + grouping: Optional[List[Dict]] = None + + class RunId(BaseModel): run_id: str state: Optional[State] = None diff --git a/tests/unit/cli/workbench/test_runs_commands.py b/tests/unit/cli/workbench/test_runs_commands.py index d3d823a0..a8eb9cfa 100644 --- a/tests/unit/cli/workbench/test_runs_commands.py +++ b/tests/unit/cli/workbench/test_runs_commands.py @@ -5,10 +5,15 @@ from click import Group from dnastack.cli.commands.workbench.runs.commands import init_runs_commands +import json + +from requests import Response + from dnastack.client.workbench.ewes.models import ( ExtendedRunListOptions, BatchRunRequest, BatchRunResponse, - MinimalExtendedRun + MinimalExtendedRun, OrchestrationRunsResponse, EngineParamPreset ) +from dnastack.http.session import ClientError, ServerError from dnastack.client.workbench.common.models import State from dnastack.client.workbench.storage.models import StorageAccount @@ -472,5 +477,128 @@ def test_submit_run_request_sample_fails_when_namespace_has_multiple_storage_acc self.mock_ewes_client.submit_batch.assert_not_called() +class TestRunsOrchestrateCommand(unittest.TestCase): + """Unit tests for runs orchestrate command""" + + def setUp(self): + self.runner = CliRunner() + self.mock_ewes_client = Mock() + self.mock_ewes_client.namespace = 'test-ns' + self.mock_ewes_client.orchestrate.return_value = OrchestrationRunsResponse(orchestration_runs=[ + {'samples': [{'id': 's1', 'storage_account_id': 'sa-1'}], + 'runs': [{'run_id': None, 'state': None, 'reused': False}]}, + ]) + engine = Mock(default=True, id='engine-1') + self.mock_ewes_client.list_engines.return_value = [engine] + self.mock_ewes_client.list_engine_param_presets.return_value = [ + EngineParamPreset(id='p1', name='other', default=False, preset_values={'other': 1}, engine_id='engine-1'), + EngineParamPreset(id='p2', name='default', default=True, preset_values={'cpu': 4}, engine_id='engine-1'), + ] + self.base_args = ['orchestrate', '--workflow', 'wf-1', '--version', 'v1', '--storage-account', 'sa-1'] + + patcher = patch('dnastack.cli.commands.workbench.runs.commands.get_ewes_client', + return_value=self.mock_ewes_client) + patcher.start() + self.addCleanup(patcher.stop) + + self.group = Group() + init_runs_commands(self.group) + + def _invoke(self, *extra): + return self.runner.invoke(self.group, [*self.base_args, *extra]) + + def _sent(self) -> dict: + request = self.mock_ewes_client.orchestrate.call_args[0][0] + return request.model_dump(exclude_unset=True) + + def test_request_has_no_ingest_variants_and_no_sample_groups(self): + for extra in ([], ['--dry-run']): + with self.subTest(extra=extra): + result = self._invoke('--sample', 's1', '--sample', 's2', *extra) + + self.assertEqual(result.exit_code, 0, result.output) + sent = self._sent() + self.assertNotIn('sample_groups', sent) + self.assertNotIn('ingest_variants', sent['request_templates'][0]) + self.assertEqual(sent['dry_run'], bool(extra)) + + def test_no_ingest_variants_sends_false(self): + result = self._invoke('--sample', 's1', '--no-ingest-variants') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertIs(self._sent()['request_templates'][0]['ingest_variants'], False) + + def test_storage_account_lands_on_every_sample(self): + result = self._invoke('--sample', 's1', '--sample', 's2') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(self._sent()['samples'], + [{'id': 's1', 'storage_account_id': 'sa-1'}, {'id': 's2', 'storage_account_id': 'sa-1'}]) + + def test_workflow_and_default_engine_are_sent(self): + result = self._invoke('--sample', 's1') + + self.assertEqual(result.exit_code, 0, result.output) + sent = self._sent() + template = sent['request_templates'][0] + self.assertEqual((template['workflow_id'], template['workflow_version_id'], template['workflow_url']), + ('wf-1', 'v1', 'wf-1/v1')) + self.assertEqual((sent['engine_id'], template['engine_id']), ('engine-1', 'engine-1')) + + def test_without_engine_params_sends_engine_id_and_default_preset_values(self): + result = self._invoke('--sample', 's1') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(self._sent()['request_templates'][0]['default_workflow_engine_parameters'], + {'engine_id': 'engine-1', 'cpu': 4}) + + def test_engine_params_flag_sends_the_given_values(self): + result = self._invoke('--sample', 's1', '--engine-params', '{"memory": "8G"}') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(self._sent()['request_templates'][0]['default_workflow_engine_parameters'], + {'memory': '8G'}) + self.mock_ewes_client.list_engine_param_presets.assert_not_called() + + def test_without_default_preset_sends_the_engine_id_only(self): + self.mock_ewes_client.list_engine_param_presets.return_value = [] + + result = self._invoke('--sample', 's1') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(self._sent()['request_templates'][0]['default_workflow_engine_parameters'], + {'engine_id': 'engine-1'}) + + def test_prints_the_server_response_as_json(self): + result = self._invoke('--sample', 's1') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(json.loads(result.output)['orchestration_runs'][0]['samples'][0]['id'], 's1') + + def test_without_sample_fails_and_calls_nothing(self): + result = self._invoke() + + self.assertNotEqual(result.exit_code, 0) + self.assertIn('--sample', result.output) + self.mock_ewes_client.orchestrate.assert_not_called() + + def test_server_refusals_print_the_message_and_exit_non_zero(self): + refusals = [ + (ClientError, 422, "Grouping rule 'by-family' of wf-1 v1 timed out after 5 seconds"), + (ServerError, 503, 'Could not read the selected samples. No runs were created. Try again.'), + ] + for error_class, status, msg in refusals: + with self.subTest(status=status): + response = Response() + response.status_code = status + response._content = json.dumps({'msg': msg}).encode() + self.mock_ewes_client.orchestrate.side_effect = error_class(response) + + result = self._invoke('--sample', 's1') + + self.assertNotEqual(result.exit_code, 0) + self.assertIn(msg, result.output) + + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/tests/unit/client/workbench/ewes/test_ewes_client.py b/tests/unit/client/workbench/ewes/test_ewes_client.py index f3fe3db6..97c62608 100644 --- a/tests/unit/client/workbench/ewes/test_ewes_client.py +++ b/tests/unit/client/workbench/ewes/test_ewes_client.py @@ -3,7 +3,8 @@ from unittest.mock import Mock, patch, MagicMock from dnastack.client.workbench.ewes.client import EWesClient -from dnastack.client.workbench.ewes.models import SimpleSample, ExtendedRunStatus +from dnastack.client.workbench.ewes.models import SimpleSample, ExtendedRunStatus, OrchestrationRequest, \ + OrchestrationRunRequestTemplate from dnastack.client.models import ServiceEndpoint @@ -81,3 +82,35 @@ def test_update_run_samples_with_empty_list(self, mock_create_session): if __name__ == '__main__': unittest.main() + + +class TestEWesClientOrchestrate(unittest.TestCase): + """Unit tests for EWesClient.orchestrate method""" + + @patch.object(EWesClient, 'create_http_session') + def test_orchestrate_posts_only_the_fields_that_were_set(self, mock_create_session): + mock_session = MagicMock() + mock_create_session.return_value.__enter__ = Mock(return_value=mock_session) + mock_create_session.return_value.__exit__ = Mock(return_value=False) + mock_session.post.return_value.json.return_value = { + 'orchestration_runs': [{'samples': [{'id': 's1'}], 'runs': [{'run_id': None, 'reused': False}]}], + 'grouping': [{'workflow_id': 'wf-1', 'rule': 'family', 'excluded': []}], + } + request = OrchestrationRequest( + samples=[SimpleSample(id='s1', storage_account_id='sa-1')], + request_templates=[OrchestrationRunRequestTemplate( + workflow_id='wf-1', workflow_version_id='v1', workflow_url='wf-1/v1', workflow_type='WDL')], + dry_run=True) + + result = EWesClient(ServiceEndpoint(url='https://api.example.com/'), 'test-namespace').orchestrate(request) + + url, body = mock_session.post.call_args.args[0], mock_session.post.call_args.kwargs['json'] + self.assertEqual(url, 'https://api.example.com/test-namespace/ga4gh/wes/v1/runs/orchestrate') + self.assertEqual(body, { + 'samples': [{'id': 's1', 'storage_account_id': 'sa-1'}], + 'request_templates': [{'workflow_id': 'wf-1', 'workflow_version_id': 'v1', + 'workflow_url': 'wf-1/v1', 'workflow_type': 'WDL'}], + 'dry_run': True, + }) + self.assertEqual(result.orchestration_runs[0].runs[0]['reused'], False) + self.assertEqual(result.grouping[0]['rule'], 'family') From 95a8daea469202659929b09edb563002b8013792 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milan=20P=C3=A1nik?= Date: Wed, 2 Dec 2026 12:49:26 -0500 Subject: [PATCH 2/3] [CU-1k5fpdaa5gp] Address review of runs orchestrate: narrow the missing-preset error, test the command Co-Authored-By: Claude Sonnet 5.5 --- .../cli/commands/workbench/runs/commands.py | 13 +- dnastack/client/workbench/ewes/client.py | 3 +- .../unit/cli/workbench/test_runs_commands.py | 117 ++++++++++++++++-- 3 files changed, 119 insertions(+), 14 deletions(-) diff --git a/dnastack/cli/commands/workbench/runs/commands.py b/dnastack/cli/commands/workbench/runs/commands.py index d9f222de..d588fe74 100644 --- a/dnastack/cli/commands/workbench/runs/commands.py +++ b/dnastack/cli/commands/workbench/runs/commands.py @@ -1,6 +1,7 @@ import os import uuid from functools import cache +from http import HTTPStatus from typing import Optional, Iterable, List import click @@ -23,6 +24,7 @@ from dnastack.client.workbench.ewes.models import LogType from dnastack.common.json_argument_parser import JsonLike, parse_and_merge_arguments, merge, merge_param_json_data from dnastack.common.tracing import Span +from dnastack.http.session import ClientError def _get_default_engine_id(ewes_client: EWesClient) -> str: @@ -43,9 +45,12 @@ def _resolve_engine_parameters(ewes_client: EWesClient, engine_id: str, engine_p resolved = merge_param_json_data(kv_pairs_list, json_literals_list, files_list) for param_id in param_ids_list or []: try: - merge(resolved, ewes_client.get_engine_param_preset(engine_id, param_id).preset_values) - except Exception as e: + preset = ewes_client.get_engine_param_preset(engine_id, param_id) + except ClientError as e: + if e.response.status_code != HTTPStatus.NOT_FOUND: + raise raise UnableToFindParameterError(f"Unable to find engine parameter preset with id {param_id}. {e}") + merge(resolved, preset.preset_values) return resolved @@ -734,7 +739,7 @@ def get_default_engine_id(): ArgumentSpec( name='tags', help='Set the tags for all runs. ' - 'Tags can be any JSON-like value, such as inline JSON, command separated key value pairs or ' + 'Tags must be a JSON object, given as inline JSON, comma separated key=value pairs or ' 'a json file referenced preceded by the "@" symbol.', type=JsonLike, ), @@ -798,8 +803,8 @@ def orchestrate(context: Optional[str], **template_fields, )], engine_id=engine_id, - tags=tags.parsed_value() if tags else None, dry_run=bool(dry_run), + **({'tags': tags.parsed_value()} if tags else {}), ) click.echo(to_json(normalize(ewes_client.orchestrate(request)))) diff --git a/dnastack/client/workbench/ewes/client.py b/dnastack/client/workbench/ewes/client.py index 987b1854..d89a381a 100644 --- a/dnastack/client/workbench/ewes/client.py +++ b/dnastack/client/workbench/ewes/client.py @@ -11,7 +11,8 @@ from dnastack.client.workbench.ewes.models import ExtendedRunEvents, WesServiceInfo, ExtendedRunStatus, \ ExtendedRunListOptions, \ ExtendedRunListResponse, ExtendedRun, RunId, WorkbenchApiError, BatchActionResult, MinimalExtendedRun, \ - BatchRunResponse, BatchRunRequest, ExtendedRunRequest, OrchestrationRequest, OrchestrationRunsResponse, Log, TaskListOptions, \ + BatchRunResponse, BatchRunRequest, ExtendedRunRequest, OrchestrationRequest, OrchestrationRunsResponse, \ + Log, TaskListOptions, \ TaskListResponse, LogType, ExecutionEngineListOptions, ExecutionEngineListResponse, ExecutionEngine, \ EngineParamPreset, EngineParamPresetListOptions, EngineParamPresetListResponse, \ EngineHealthCheck, EngineHealthCheckListOptions, EngineHealthCheckListResponse, \ diff --git a/tests/unit/cli/workbench/test_runs_commands.py b/tests/unit/cli/workbench/test_runs_commands.py index a8eb9cfa..1f1dfcb5 100644 --- a/tests/unit/cli/workbench/test_runs_commands.py +++ b/tests/unit/cli/workbench/test_runs_commands.py @@ -13,6 +13,7 @@ ExtendedRunListOptions, BatchRunRequest, BatchRunResponse, MinimalExtendedRun, OrchestrationRunsResponse, EngineParamPreset ) +from dnastack.cli.helpers.exporter import normalize from dnastack.http.session import ClientError, ServerError from dnastack.client.workbench.common.models import State from dnastack.client.workbench.storage.models import StorageAccount @@ -484,10 +485,10 @@ def setUp(self): self.runner = CliRunner() self.mock_ewes_client = Mock() self.mock_ewes_client.namespace = 'test-ns' - self.mock_ewes_client.orchestrate.return_value = OrchestrationRunsResponse(orchestration_runs=[ - {'samples': [{'id': 's1', 'storage_account_id': 'sa-1'}], - 'runs': [{'run_id': None, 'state': None, 'reused': False}]}, - ]) + self.mock_ewes_client.orchestrate.return_value = OrchestrationRunsResponse( + orchestration_runs=[{'samples': [{'id': 's1', 'storage_account_id': 'sa-1'}], + 'runs': [{'run_id': None, 'state': None, 'reused': False}]}], + grouping=[{'workflow_id': 'wf-1', 'workflow_version_id': 'v1', 'rule': 'family', 'excluded': []}]) engine = Mock(default=True, id='engine-1') self.mock_ewes_client.list_engines.return_value = [engine] self.mock_ewes_client.list_engine_param_presets.return_value = [ @@ -501,12 +502,26 @@ def setUp(self): patcher.start() self.addCleanup(patcher.stop) + storage_patcher = patch('dnastack.cli.commands.workbench.utils.get_storage_client') + self.mock_storage_client = storage_patcher.start().return_value + self.addCleanup(storage_patcher.stop) + self.group = Group() init_runs_commands(self.group) def _invoke(self, *extra): return self.runner.invoke(self.group, [*self.base_args, *extra]) + def _invoke_without_storage_account(self, *extra): + return self.runner.invoke(self.group, ['orchestrate', '--workflow', 'wf-1', '--version', 'v1', *extra]) + + @staticmethod + def _http_error(error_class, status, msg): + response = Response() + response.status_code = status + response._content = json.dumps({'msg': msg}).encode() + return error_class(response) + def _sent(self) -> dict: request = self.mock_ewes_client.orchestrate.call_args[0][0] return request.model_dump(exclude_unset=True) @@ -573,7 +588,7 @@ def test_prints_the_server_response_as_json(self): result = self._invoke('--sample', 's1') self.assertEqual(result.exit_code, 0, result.output) - self.assertEqual(json.loads(result.output)['orchestration_runs'][0]['samples'][0]['id'], 's1') + self.assertEqual(json.loads(result.output), normalize(self.mock_ewes_client.orchestrate.return_value)) def test_without_sample_fails_and_calls_nothing(self): result = self._invoke() @@ -589,16 +604,100 @@ def test_server_refusals_print_the_message_and_exit_non_zero(self): ] for error_class, status, msg in refusals: with self.subTest(status=status): - response = Response() - response.status_code = status - response._content = json.dumps({'msg': msg}).encode() - self.mock_ewes_client.orchestrate.side_effect = error_class(response) + self.mock_ewes_client.orchestrate.side_effect = self._http_error(error_class, status, msg) result = self._invoke('--sample', 's1') self.assertNotEqual(result.exit_code, 0) self.assertIn(msg, result.output) + def test_engine_params_preset_id_is_merged_into_the_request(self): + self.mock_ewes_client.get_engine_param_preset.return_value = EngineParamPreset( + id='my-preset', name='my', preset_values={'cpu': 8}, engine_id='engine-1') + + result = self._invoke('--sample', 's1', '--engine-params', 'my-preset,memory=8G') + + self.assertEqual(result.exit_code, 0, result.output) + self.mock_ewes_client.get_engine_param_preset.assert_called_once_with('engine-1', 'my-preset') + self.assertEqual(self._sent()['request_templates'][0]['default_workflow_engine_parameters'], + {'memory': '8G', 'cpu': 8}) + + def test_missing_engine_param_preset_fails_and_calls_nothing(self): + self.mock_ewes_client.get_engine_param_preset.side_effect = self._http_error(ClientError, 404, 'no such preset') + + result = self._invoke('--sample', 's1', '--engine-params', 'my-preset') + + self.assertNotEqual(result.exit_code, 0) + self.assertIn('UnableToFindParameterError: Unable to find engine parameter preset with id my-preset', + result.output) + self.mock_ewes_client.orchestrate.assert_not_called() + + def test_other_preset_lookup_errors_are_not_reported_as_a_missing_preset(self): + for error in (self._http_error(ClientError, 403, 'forbidden'), + self._http_error(ServerError, 503, 'unavailable'), + ConnectionError('connection reset')): + with self.subTest(error=error): + self.mock_ewes_client.get_engine_param_preset.side_effect = error + + result = self._invoke('--sample', 's1', '--engine-params', 'my-preset') + + self.assertNotEqual(result.exit_code, 0) + self.assertNotIn('Unable to find engine parameter preset', result.output) + self.assertIn(type(error).__name__, result.output) + self.mock_ewes_client.orchestrate.assert_not_called() + + def test_engine_flag_is_sent_without_looking_up_the_default_engine(self): + result = self._invoke('--sample', 's1', '--engine', 'engine-2') + + self.assertEqual(result.exit_code, 0, result.output) + sent = self._sent() + self.assertEqual((sent['engine_id'], sent['request_templates'][0]['engine_id']), ('engine-2', 'engine-2')) + self.mock_ewes_client.list_engines.assert_not_called() + self.mock_ewes_client.list_engine_param_presets.assert_called_once() + self.assertEqual(self.mock_ewes_client.list_engine_param_presets.call_args[0][0], 'engine-2') + + def test_no_default_engine_fails_and_calls_nothing(self): + self.mock_ewes_client.list_engines.return_value = [Mock(default=False, id='engine-1')] + + result = self._invoke('--sample', 's1') + + self.assertNotEqual(result.exit_code, 0) + self.assertIn('No default engine found', result.output) + self.mock_ewes_client.orchestrate.assert_not_called() + + def test_tags_are_sent_exactly(self): + result = self._invoke('--sample', 's1', '--tags', '{"project": "p1", "empty": null, "n": 3}') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(self._sent()['tags'], {'project': 'p1', 'empty': None, 'n': 3}) + + def test_without_tags_none_are_sent(self): + result = self._invoke('--sample', 's1') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertNotIn('tags', self._sent()) + + def test_the_only_storage_account_is_used_when_none_is_given(self): + self.mock_storage_client.list_storage_accounts.side_effect = lambda *a, **k: iter([StorageAccount(id='sa-only')]) + + result = self._invoke_without_storage_account('--sample', 's1') + + self.assertEqual(result.exit_code, 0, result.output) + self.assertEqual(self._sent()['samples'], [{'id': 's1', 'storage_account_id': 'sa-only'}]) + + def test_zero_or_several_storage_accounts_fail_and_call_nothing(self): + cases = {'No storage accounts found': [], + '--storage-account': [StorageAccount(id='sa-1'), StorageAccount(id='sa-2')]} + for expected, accounts in cases.items(): + with self.subTest(expected=expected): + self.mock_storage_client.list_storage_accounts.side_effect = lambda *a, accounts=accounts, **k: iter(accounts) + + result = self._invoke_without_storage_account('--sample', 's1') + + self.assertNotEqual(result.exit_code, 0) + self.assertIn(expected, result.output) + self.mock_ewes_client.orchestrate.assert_not_called() + if __name__ == '__main__': unittest.main() \ No newline at end of file From a0bdc1451cc28833b793d29ac2b21fd63b06a167 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Milan=20P=C3=A1nik?= Date: Wed, 2 Dec 2026 12:50:11 -0500 Subject: [PATCH 3/3] [CU-1k5fpdaa5gp] Wrap two test lines over 120 characters Co-Authored-By: Claude Sonnet 5.5 --- tests/unit/cli/workbench/test_runs_commands.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/unit/cli/workbench/test_runs_commands.py b/tests/unit/cli/workbench/test_runs_commands.py index 1f1dfcb5..0704cab9 100644 --- a/tests/unit/cli/workbench/test_runs_commands.py +++ b/tests/unit/cli/workbench/test_runs_commands.py @@ -678,7 +678,8 @@ def test_without_tags_none_are_sent(self): self.assertNotIn('tags', self._sent()) def test_the_only_storage_account_is_used_when_none_is_given(self): - self.mock_storage_client.list_storage_accounts.side_effect = lambda *a, **k: iter([StorageAccount(id='sa-only')]) + self.mock_storage_client.list_storage_accounts.side_effect = \ + lambda *a, **k: iter([StorageAccount(id='sa-only')]) result = self._invoke_without_storage_account('--sample', 's1') @@ -690,7 +691,8 @@ def test_zero_or_several_storage_accounts_fail_and_call_nothing(self): '--storage-account': [StorageAccount(id='sa-1'), StorageAccount(id='sa-2')]} for expected, accounts in cases.items(): with self.subTest(expected=expected): - self.mock_storage_client.list_storage_accounts.side_effect = lambda *a, accounts=accounts, **k: iter(accounts) + self.mock_storage_client.list_storage_accounts.side_effect = \ + lambda *a, accounts=accounts, **k: iter(accounts) result = self._invoke_without_storage_account('--sample', 's1')