Coverage for python/lsst/pipe/base/tests/mocks/_pipeline_task.py: 22%

227 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-11-30 12:09 +0000

1# This file is part of pipe_base. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (http://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# This software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

15# This program is free software: you can redistribute it and/or modify 

16# it under the terms of the GNU General Public License as published by 

17# the Free Software Foundation, either version 3 of the License, or 

18# (at your option) any later version. 

19# 

20# This program is distributed in the hope that it will be useful, 

21# but WITHOUT ANY WARRANTY; without even the implied warranty of 

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

25# You should have received a copy of the GNU General Public License 

26# along with this program. If not, see <http://www.gnu.org/licenses/>. 

27from __future__ import annotations 

28 

29from lsst.pipe.base.connectionTypes import BaseInput, Output 

30 

31__all__ = ( 

32 "DynamicConnectionConfig", 

33 "DynamicTestPipelineTask", 

34 "DynamicTestPipelineTaskConfig", 

35 "MockPipelineTask", 

36 "MockPipelineTaskConfig", 

37 "mock_task_defs", 

38 "mock_pipeline_graph", 

39) 

40 

41import dataclasses 

42import logging 

43from collections.abc import Collection, Iterable, Mapping 

44from typing import TYPE_CHECKING, Any, ClassVar, TypeVar 

45 

46from lsst.daf.butler import DataCoordinate, DatasetRef, DeferredDatasetHandle, SerializedDatasetType 

47from lsst.pex.config import Config, ConfigDictField, ConfigurableField, Field, ListField 

48from lsst.utils.doImport import doImportType 

49from lsst.utils.introspection import get_full_type_name 

50from lsst.utils.iteration import ensure_iterable 

51 

52from ... import automatic_connection_constants as acc 

53from ... import connectionTypes as cT 

54from ...config import PipelineTaskConfig 

55from ...connections import InputQuantizedConnection, OutputQuantizedConnection, PipelineTaskConnections 

56from ...pipeline import TaskDef 

57from ...pipeline_graph import PipelineGraph 

58from ...pipelineTask import PipelineTask 

59from ._data_id_match import DataIdMatch 

60from ._storage_class import MockDataset, MockDatasetQuantum, MockStorageClass, get_mock_name 

61 

62_LOG = logging.getLogger(__name__) 

63 

64if TYPE_CHECKING: 

65 from ..._quantumContext import QuantumContext 

66 

67 

68_T = TypeVar("_T", bound=cT.BaseConnection) 

69 

70 

71def mock_task_defs( 

72 originals: Iterable[TaskDef], 

73 unmocked_dataset_types: Iterable[str] = (), 

74 force_failures: Mapping[str, tuple[str, type[Exception] | None]] | None = None, 

75) -> list[TaskDef]: 

76 """Create mocks for an iterable of TaskDefs. 

77 

78 Parameters 

79 ---------- 

80 originals : `~collections.abc.Iterable` [ `TaskDef` ] 

81 Original tasks and configuration to mock. 

82 unmocked_dataset_types : `~collections.abc.Iterable` [ `str` ], optional 

83 Names of overall-input dataset types that should not be replaced with 

84 mocks. 

85 force_failures : `~collections.abc.Mapping` [ `str`, `tuple` [ `str`, \ 

86 `type` [ `Exception` ] or `None` ] ] 

87 Mapping from original task label to a 2-tuple indicating that some 

88 quanta should raise an exception when executed. The first entry is a 

89 data ID match using the butler expression language (i.e. a string of 

90 the sort passed ass the ``where`` argument to butler query methods), 

91 while the second is the type of exception to raise when the quantum 

92 data ID matches the expression. An exception type of `None` uses 

93 the default, `ValueError`. 

94 

95 Returns 

96 ------- 

97 mocked : `list` [ `TaskDef` ] 

98 List of `TaskDef` objects using `MockPipelineTask` configurations that 

99 target the original tasks, in the same order. 

100 """ 

101 unmocked_dataset_types = tuple(unmocked_dataset_types) 

102 if force_failures is None: 

103 force_failures = {} 

104 results: list[TaskDef] = [] 

105 for original_task_def in originals: 

106 config = MockPipelineTaskConfig() 

107 config.original.retarget(original_task_def.taskClass) 

108 config.original = original_task_def.config 

109 config.unmocked_dataset_types.extend(unmocked_dataset_types) 

110 if original_task_def.label in force_failures: 

111 condition, exception_type = force_failures[original_task_def.label] 

112 config.fail_condition = condition 

113 if exception_type is not None: 

114 config.fail_exception = get_full_type_name(exception_type) 

115 mock_task_def = TaskDef( 

116 config=config, taskClass=MockPipelineTask, label=get_mock_name(original_task_def.label) 

117 ) 

118 results.append(mock_task_def) 

119 return results 

120 

121 

122def mock_pipeline_graph( 

123 original_graph: PipelineGraph, 

124 unmocked_dataset_types: Iterable[str] = (), 

125 force_failures: Mapping[str, tuple[str, type[Exception] | None]] | None = None, 

126) -> PipelineGraph: 

127 """Create mocks for a full pipeline graph. 

128 

129 Parameters 

130 ---------- 

131 original_graph : `~..pipeline_graph.PipelineGraph` 

132 Original tasks and configuration to mock. 

133 unmocked_dataset_types : `~collections.abc.Iterable` [ `str` ], optional 

134 Names of overall-input dataset types that should not be replaced with 

135 mocks. 

136 force_failures : `~collections.abc.Mapping` [ `str`, `tuple` [ `str`, \ 

137 `type` [ `Exception` ] or `None` ] ] 

138 Mapping from original task label to a 2-tuple indicating that some 

139 quanta should raise an exception when executed. The first entry is a 

140 data ID match using the butler expression language (i.e. a string of 

141 the sort passed as the ``where`` argument to butler query methods), 

142 while the second is the type of exception to raise when the quantum 

143 data ID matches the expression. An exception type of `None` uses 

144 the default, `ValueError`. 

145 

146 Returns 

147 ------- 

148 mocked : `~..pipeline_graph.PipelineGraph` 

149 Pipeline graph using `MockPipelineTask` configurations that target the 

150 original tasks. Never resolved. 

151 """ 

152 unmocked_dataset_types = tuple(unmocked_dataset_types) 

153 if force_failures is None: 

154 force_failures = {} 

155 result = PipelineGraph(description=original_graph.description) 

156 for original_task_node in original_graph.tasks.values(): 

157 config = MockPipelineTaskConfig() 

158 config.original.retarget(original_task_node.task_class) 

159 config.original = original_task_node.config 

160 config.unmocked_dataset_types.extend(unmocked_dataset_types) 

161 if original_task_node.label in force_failures: 

162 condition, exception_type = force_failures[original_task_node.label] 

163 config.fail_condition = condition 

164 if exception_type is not None: 

165 config.fail_exception = get_full_type_name(exception_type) 

166 result.add_task(get_mock_name(original_task_node.label), MockPipelineTask, config=config) 

167 return result 

168 

169 

170class BaseTestPipelineTaskConnections(PipelineTaskConnections, dimensions=()): 

171 pass 

172 

173 

174class BaseTestPipelineTaskConfig(PipelineTaskConfig, pipelineConnections=BaseTestPipelineTaskConnections): 

175 fail_condition = Field[str]( 

176 dtype=str, 

177 default="", 

178 doc=( 

179 "Condition on Data ID to raise an exception. String expression which includes attributes of " 

180 "quantum data ID using a syntax of daf_butler user expressions (e.g. 'visit = 123')." 

181 ), 

182 ) 

183 

184 fail_exception = Field[str]( 

185 dtype=str, 

186 default="builtins.ValueError", 

187 doc=( 

188 "Class name of the exception to raise when fail condition is triggered. Can be " 

189 "'lsst.pipe.base.NoWorkFound' to specify non-failure exception." 

190 ), 

191 ) 

192 

193 def data_id_match(self) -> DataIdMatch | None: 

194 if not self.fail_condition: 

195 return None 

196 return DataIdMatch(self.fail_condition) 

197 

198 

199class BaseTestPipelineTask(PipelineTask): 

200 """A base class for test-utility `PipelineTask` classes that read and write 

201 mock datasets `runQuantum`. 

202 

203 Notes 

204 ----- 

205 This class overrides `runQuantum` to read inputs and write a bit of 

206 provenance into all of its outputs (always `MockDataset` instances). It 

207 can also be configured to raise exceptions on certain data IDs. It reads 

208 `MockDataset` inputs and simulates reading inputs of other types by 

209 creating `MockDataset` inputs from their DatasetRefs. 

210 

211 Subclasses are responsible for defining connections, but init-input and 

212 init-output connections are not supported at runtime (they may be present 

213 as long as the task is never constructed). All output connections must 

214 use mock storage classes. `..Input` and `..PrerequisiteInput` connections 

215 that do not use mock storage classes will be handled by constructing a 

216 `MockDataset` from the `~lsst.daf.butler.DatasetRef` rather than actually 

217 reading them. 

218 """ 

219 

220 ConfigClass: ClassVar[type[PipelineTaskConfig]] = BaseTestPipelineTaskConfig 

221 

222 def __init__( 

223 self, 

224 *, 

225 config: BaseTestPipelineTaskConfig, 

226 initInputs: Mapping[str, Any], 

227 **kwargs: Any, 

228 ): 

229 super().__init__(config=config, **kwargs) 

230 self.fail_exception: type | None = None 

231 self.data_id_match = self.config.data_id_match() 

232 if self.data_id_match: 

233 self.fail_exception = doImportType(self.config.fail_exception) 

234 # Look for, check, and record init-inputs. 

235 task_connections = self.ConfigClass.ConnectionsClass(config=config) 

236 mock_dataset_quantum = MockDatasetQuantum(task_label=self.getName(), data_id={}, inputs={}) 

237 for connection_name in task_connections.initInputs: 

238 input_dataset = initInputs[connection_name] 

239 if not isinstance(input_dataset, MockDataset): 

240 raise TypeError( 

241 f"Expected MockDataset instance for init-input {self.getName()}.{connection_name}: " 

242 f"got {input_dataset!r} of type {type(input_dataset)!r}." 

243 ) 

244 connection = task_connections.allConnections[connection_name] 

245 if input_dataset.dataset_type.name != connection.name: 

246 raise RuntimeError( 

247 f"Incorrect dataset type name for init-input {self.getName()}.{connection_name}: " 

248 f"got {input_dataset.dataset_type.name!r}, expected {connection.name!r}." 

249 ) 

250 if input_dataset.storage_class != connection.storageClass: 

251 raise RuntimeError( 

252 f"Incorrect storage class for init-input {self.getName()}.{connection_name}: " 

253 f"got {input_dataset.storage_class!r}, expected {connection.storageClass!r}." 

254 ) 

255 # To avoid very deep provenance we trim inputs to a single 

256 # level. 

257 input_dataset.quantum = None 

258 mock_dataset_quantum.inputs[connection_name] = [input_dataset] 

259 # Add init-outputs as task instance attributes. 

260 for connection_name in task_connections.initOutputs: 

261 connection = task_connections.allConnections[connection_name] 

262 output_dataset = MockDataset( 

263 dataset_id=None, # the task has no way to get this 

264 dataset_type=SerializedDatasetType( 

265 name=connection.name, 

266 storageClass=connection.storageClass, 

267 dimensions=[], 

268 ), 

269 data_id={}, 

270 run=None, # task also has no way to get this 

271 quantum=mock_dataset_quantum, 

272 output_connection_name=connection_name, 

273 ) 

274 setattr(self, connection_name, output_dataset) 

275 

276 config: BaseTestPipelineTaskConfig 

277 

278 def runQuantum( 

279 self, 

280 butlerQC: QuantumContext, 

281 inputRefs: InputQuantizedConnection, 

282 outputRefs: OutputQuantizedConnection, 

283 ) -> None: 

284 # docstring is inherited from the base class 

285 quantum = butlerQC.quantum 

286 

287 _LOG.info("Mocking execution of task '%s' on quantum %s", self.getName(), quantum.dataId) 

288 

289 assert quantum.dataId is not None, "Quantum DataId cannot be None" 

290 

291 # Possibly raise an exception. 

292 if self.data_id_match is not None and self.data_id_match.match(quantum.dataId): 

293 _LOG.info("Simulating failure of task '%s' on quantum %s", self.getName(), quantum.dataId) 

294 message = f"Simulated failure: task={self.getName()} dataId={quantum.dataId}" 

295 assert self.fail_exception is not None, "Exception type must be defined" 

296 raise self.fail_exception(message) 

297 

298 # Populate the bit of provenance we store in all outputs. 

299 _LOG.info("Reading input data for task '%s' on quantum %s", self.getName(), quantum.dataId) 

300 mock_dataset_quantum = MockDatasetQuantum( 

301 task_label=self.getName(), data_id=dict(quantum.dataId.mapping), inputs={} 

302 ) 

303 for name, refs in inputRefs: 

304 inputs_list = [] 

305 ref: DatasetRef 

306 for ref in ensure_iterable(refs): 

307 if isinstance(ref.datasetType.storageClass, MockStorageClass): 

308 input_dataset = butlerQC.get(ref) 

309 if isinstance(input_dataset, DeferredDatasetHandle): 

310 input_dataset = input_dataset.get() 

311 if not isinstance(input_dataset, MockDataset): 

312 raise TypeError( 

313 f"Expected MockDataset instance for {ref}; " 

314 f"got {input_dataset!r} of type {type(input_dataset)!r}." 

315 ) 

316 # To avoid very deep provenance we trim inputs to a single 

317 # level. 

318 input_dataset.quantum = None 

319 else: 

320 input_dataset = MockDataset( 

321 dataset_id=ref.id, 

322 dataset_type=ref.datasetType.to_simple(), 

323 data_id=dict(ref.dataId.mapping), 

324 run=ref.run, 

325 ) 

326 inputs_list.append(input_dataset) 

327 mock_dataset_quantum.inputs[name] = inputs_list 

328 

329 # store mock outputs 

330 for name, refs in outputRefs: 

331 for ref in ensure_iterable(refs): 

332 output = MockDataset( 

333 dataset_id=ref.id, 

334 dataset_type=ref.datasetType.to_simple(), 

335 data_id=dict(ref.dataId.mapping), 

336 run=ref.run, 

337 quantum=mock_dataset_quantum, 

338 output_connection_name=name, 

339 ) 

340 butlerQC.put(output, ref) 

341 

342 _LOG.info("Finished mocking task '%s' on quantum %s", self.getName(), quantum.dataId) 

343 

344 

345class MockPipelineDefaultTargetConnections(PipelineTaskConnections, dimensions=()): 

346 pass 

347 

348 

349class MockPipelineDefaultTargetConfig( 

350 PipelineTaskConfig, pipelineConnections=MockPipelineDefaultTargetConnections 

351): 

352 pass 

353 

354 

355class MockPipelineDefaultTargetTask(PipelineTask): 

356 """A `~lsst.pipe.base.PipelineTask` class used as the default target for 

357 ``MockPipelineTaskConfig.original``. 

358 

359 This is effectively a workaround for `lsst.pex.config.ConfigurableField` 

360 not supporting ``optional=True``, but that is generally a reasonable 

361 limitation for production code and it wouldn't make sense just to support 

362 test utilities. 

363 """ 

364 

365 ConfigClass = MockPipelineDefaultTargetConfig 

366 

367 

368class MockPipelineTaskConnections(BaseTestPipelineTaskConnections, dimensions=()): 

369 """A connections class that creates mock connections from the connections 

370 of a real PipelineTask. 

371 """ 

372 

373 def __init__(self, *, config: MockPipelineTaskConfig): 

374 self.original: PipelineTaskConnections = config.original.connections.ConnectionsClass( 

375 config=config.original.value 

376 ) 

377 self.dimensions.update(self.original.dimensions) 

378 self.unmocked_dataset_types = frozenset(config.unmocked_dataset_types) 

379 for name, connection in self.original.allConnections.items(): 

380 if connection.name not in self.unmocked_dataset_types: 

381 if connection.storageClass in ( 

382 acc.CONFIG_INIT_OUTPUT_STORAGE_CLASS, 

383 acc.METADATA_OUTPUT_STORAGE_CLASS, 

384 acc.LOG_OUTPUT_STORAGE_CLASS, 

385 ): 

386 # We don't mock the automatic output connections, so if 

387 # they're used as an input in any other connection, we 

388 # can't mock them there either. 

389 storage_class_name = connection.storageClass 

390 else: 

391 # We register the mock storage class with the global 

392 # singleton here, but can only put its name in the 

393 # connection. That means the same global singleton (or one 

394 # that also has these registrations) has to be available 

395 # whenever this dataset type is used. 

396 storage_class_name = MockStorageClass.get_or_register_mock(connection.storageClass).name 

397 kwargs: dict[str, Any] = {} 

398 if hasattr(connection, "dimensions"): 

399 connection_dimensions = set(connection.dimensions) 

400 # Replace the generic "skypix" placeholder with htm7, since 

401 # that requires the dataset type to have already been 

402 # registered. 

403 if "skypix" in connection_dimensions: 

404 connection_dimensions.remove("skypix") 

405 connection_dimensions.add("htm7") 

406 kwargs["dimensions"] = connection_dimensions 

407 connection = dataclasses.replace( 

408 connection, 

409 name=get_mock_name(connection.name), 

410 storageClass=storage_class_name, 

411 **kwargs, 

412 ) 

413 elif name in self.original.outputs: 

414 raise ValueError(f"Unmocked dataset type {connection.name!r} cannot be used as an output.") 

415 elif name in self.original.initInputs: 

416 raise ValueError( 

417 f"Unmocked dataset type {connection.name!r} cannot be used as an init-input." 

418 ) 

419 elif name in self.original.initOutputs: 

420 raise ValueError( 

421 f"Unmocked dataset type {connection.name!r} cannot be used as an init-output." 

422 ) 

423 setattr(self, name, connection) 

424 

425 def getSpatialBoundsConnections(self) -> Iterable[str]: 

426 return self.original.getSpatialBoundsConnections() 

427 

428 def getTemporalBoundsConnections(self) -> Iterable[str]: 

429 return self.original.getTemporalBoundsConnections() 

430 

431 def adjustQuantum( 

432 self, 

433 inputs: dict[str, tuple[BaseInput, Collection[DatasetRef]]], 

434 outputs: dict[str, tuple[Output, Collection[DatasetRef]]], 

435 label: str, 

436 data_id: DataCoordinate, 

437 ) -> tuple[ 

438 Mapping[str, tuple[BaseInput, Collection[DatasetRef]]], 

439 Mapping[str, tuple[Output, Collection[DatasetRef]]], 

440 ]: 

441 # Convert the given mappings from the mock dataset types to the 

442 # original dataset types they were produced from. 

443 original_inputs = {} 

444 for connection_name, (_, mock_refs) in inputs.items(): 

445 original_connection = getattr(self.original, connection_name) 

446 if original_connection.name in self.unmocked_dataset_types: 

447 refs = mock_refs 

448 else: 

449 refs = MockStorageClass.unmock_dataset_refs(mock_refs) 

450 original_inputs[connection_name] = (original_connection, refs) 

451 original_outputs = {} 

452 for connection_name, (_, mock_refs) in outputs.items(): 

453 original_connection = getattr(self.original, connection_name) 

454 if original_connection.name in self.unmocked_dataset_types: 

455 refs = mock_refs 

456 else: 

457 refs = MockStorageClass.unmock_dataset_refs(mock_refs) 

458 original_outputs[connection_name] = (original_connection, refs) 

459 # Call adjustQuantum on the original connections class. 

460 adjusted_original_inputs, adjusted_original_outputs = self.original.adjustQuantum( 

461 original_inputs, original_outputs, label, data_id 

462 ) 

463 # Convert the results back to the mock dataset type.s 

464 adjusted_inputs = {} 

465 for connection_name, (original_connection, original_refs) in adjusted_original_inputs.items(): 

466 if original_connection.name in self.unmocked_dataset_types: 

467 refs = original_refs 

468 else: 

469 refs = MockStorageClass.mock_dataset_refs(original_refs) 

470 adjusted_inputs[connection_name] = (getattr(self, connection_name), refs) 

471 adjusted_outputs = {} 

472 for connection_name, (original_connection, original_refs) in adjusted_original_outputs.items(): 

473 if original_connection.name in self.unmocked_dataset_types: 

474 refs = original_refs 

475 else: 

476 refs = MockStorageClass.mock_dataset_refs(original_refs) 

477 adjusted_outputs[connection_name] = (getattr(self, connection_name), refs) 

478 return adjusted_inputs, adjusted_outputs 

479 

480 

481class MockPipelineTaskConfig(BaseTestPipelineTaskConfig, pipelineConnections=MockPipelineTaskConnections): 

482 """Configuration class for `MockPipelineTask`.""" 

483 

484 original: ConfigurableField = ConfigurableField( 

485 doc="The original task being mocked by this one.", target=MockPipelineDefaultTargetTask 

486 ) 

487 

488 unmocked_dataset_types = ListField[str]( 

489 doc=( 

490 "Names of input dataset types that should be used as-is instead " 

491 "of being mocked. May include dataset types not relevant for " 

492 "this task, which will be ignored." 

493 ), 

494 default=(), 

495 optional=False, 

496 ) 

497 

498 

499class MockPipelineTask(BaseTestPipelineTask): 

500 """A test-utility implementation of `PipelineTask` with connections 

501 generated by mocking those of a real task. 

502 

503 Notes 

504 ----- 

505 At present `MockPipelineTask` simply drops any ``initInput`` and 

506 ``initOutput`` connections present on the original, since `MockDataset` 

507 creation for those would have to happen in the code that executes the task, 

508 not in the task itself. Because `MockPipelineTask` never instantiates the 

509 mock task (just its connections class), this is a limitation on what the 

510 mocks can be used to test, not anything deeper. 

511 """ 

512 

513 ConfigClass: ClassVar[type[PipelineTaskConfig]] = MockPipelineTaskConfig 

514 

515 

516class DynamicConnectionConfig(Config): 

517 """A config class that defines a completely dynamic connection.""" 

518 

519 dataset_type_name = Field[str](doc="Name for the dataset type as seen by the butler.", dtype=str) 

520 dimensions = ListField[str](doc="Dimensions for the dataset type.", dtype=str, default=[]) 

521 storage_class = Field[str]( 

522 doc="Name of the butler storage class for the dataset type.", dtype=str, default="StructuredDataDict" 

523 ) 

524 is_calibration = Field[bool](doc="Whether this dataset type is a calibration.", dtype=bool, default=False) 

525 multiple = Field[bool]( 

526 doc="Whether this connection gets or puts multiple datasets for each quantum.", 

527 dtype=bool, 

528 default=False, 

529 ) 

530 mock_storage_class = Field[bool]( 

531 doc="Whether the storage class should actually be a mock of the storage class given.", 

532 dtype=bool, 

533 default=True, 

534 ) 

535 

536 def make_connection(self, cls: type[_T]) -> _T: 

537 storage_class = self.storage_class 

538 if self.mock_storage_class: 

539 storage_class = MockStorageClass.get_or_register_mock(storage_class).name 

540 if issubclass(cls, cT.DimensionedConnection): 

541 return cls( # type: ignore 

542 name=self.dataset_type_name, 

543 storageClass=storage_class, 

544 isCalibration=self.is_calibration, 

545 multiple=self.multiple, 

546 dimensions=frozenset(self.dimensions), 

547 ) 

548 else: 

549 return cls( 

550 name=self.dataset_type_name, 

551 storageClass=storage_class, 

552 multiple=self.multiple, 

553 ) 

554 

555 

556class DynamicTestPipelineTaskConnections(PipelineTaskConnections, dimensions=()): 

557 """A connections class whose dimensions and connections are wholly 

558 determined via configuration. 

559 """ 

560 

561 def __init__(self, *, config: DynamicTestPipelineTaskConfig): 

562 self.dimensions.update(config.dimensions) 

563 connection_config: DynamicConnectionConfig 

564 for connection_name, connection_config in config.init_inputs.items(): 

565 setattr(self, connection_name, connection_config.make_connection(cT.InitInput)) 

566 for connection_name, connection_config in config.init_outputs.items(): 

567 setattr(self, connection_name, connection_config.make_connection(cT.InitOutput)) 

568 for connection_name, connection_config in config.prerequisite_inputs.items(): 

569 setattr(self, connection_name, connection_config.make_connection(cT.PrerequisiteInput)) 

570 for connection_name, connection_config in config.inputs.items(): 

571 setattr(self, connection_name, connection_config.make_connection(cT.Input)) 

572 for connection_name, connection_config in config.outputs.items(): 

573 setattr(self, connection_name, connection_config.make_connection(cT.Output)) 

574 

575 

576class DynamicTestPipelineTaskConfig( 

577 PipelineTaskConfig, pipelineConnections=DynamicTestPipelineTaskConnections 

578): 

579 """Configuration for DynamicTestPipelineTask.""" 

580 

581 dimensions = ListField[str](doc="Dimensions for the task's quanta.", dtype=str, default=[]) 

582 init_inputs = ConfigDictField( 

583 doc=( 

584 "Init-input connections, keyed by the connection name as seen by the task. " 

585 "Must be empty if the task will be constructed." 

586 ), 

587 keytype=str, 

588 itemtype=DynamicConnectionConfig, 

589 default={}, 

590 ) 

591 init_outputs = ConfigDictField( 

592 doc=( 

593 "Init-output connections, keyed by the connection name as seen by the task. " 

594 "Must be empty if the task will be constructed." 

595 ), 

596 keytype=str, 

597 itemtype=DynamicConnectionConfig, 

598 default={}, 

599 ) 

600 prerequisite_inputs = ConfigDictField( 

601 doc="Prerequisite input connections, keyed by the connection name as seen by the task.", 

602 keytype=str, 

603 itemtype=DynamicConnectionConfig, 

604 default={}, 

605 ) 

606 inputs = ConfigDictField( 

607 doc="Regular input connections, keyed by the connection name as seen by the task.", 

608 keytype=str, 

609 itemtype=DynamicConnectionConfig, 

610 default={}, 

611 ) 

612 outputs = ConfigDictField( 

613 doc="Regular output connections, keyed by the connection name as seen by the task.", 

614 keytype=str, 

615 itemtype=DynamicConnectionConfig, 

616 default={}, 

617 ) 

618 

619 

620class DynamicTestPipelineTask(BaseTestPipelineTask): 

621 """A test-utility implementation of `PipelineTask` with dimensions and 

622 connections determined wholly from configuration. 

623 """ 

624 

625 ConfigClass: ClassVar[type[PipelineTaskConfig]] = DynamicTestPipelineTaskConfig