From 65f34db86fdb46ed97638658635989ed75af7492 Mon Sep 17 00:00:00 2001 From: larsevj Date: Mon, 13 Jan 2025 09:26:42 +0100 Subject: [PATCH] Upgrade pre-commits ruff 0.8.6 -> 0.9.1 --- .pre-commit-config.yaml | 2 +- .../forward_model_step.py | 8 +-- src/ert/callbacks.py | 3 +- src/ert/config/ert_config.py | 2 +- src/ert/config/parsing/observations_parser.py | 5 +- src/ert/ensemble_evaluator/_ensemble.py | 2 +- .../models/activerealizationsmodel.py | 2 +- src/ert/gui/simulation/experiment_panel.py | 2 +- .../gui/simulation/view/progress_widget.py | 2 +- src/ert/gui/suggestor/_suggestor_message.py | 2 +- .../customize/default_customization_view.py | 6 +-- src/ert/gui/tools/plot/plot_window.py | 2 +- .../tools/workflows/run_workflow_widget.py | 2 +- .../workflows/export_runpath.py | 2 +- .../forward_model_steps.py | 6 +-- src/ert/plugins/plugin_manager.py | 2 +- src/ert/plugins/plugin_response.py | 7 +-- .../resources/shell_scripts/copy_directory.py | 3 +- src/ert/scheduler/job.py | 2 +- src/ert/scheduler/openpbs_driver.py | 2 +- src/ert/storage/local_storage.py | 12 ++--- src/ert/storage/migration/to7.py | 6 +-- src/ert/validation/rangestring.py | 2 +- src/everest/config/control_config.py | 3 +- src/everest/config/everest_config.py | 6 +-- src/everest/export.py | 5 +- src/everest/jobs/well_tools/__init__.py | 2 +- src/everest/simulator/__init__.py | 2 +- .../ert/poly_example/Plot_correlations.ipynb | 2 +- .../forward_models/snake_oil_diff.py | 2 +- tests/ert/conftest.py | 6 +-- .../analysis/test_adaptive_localization.py | 12 ++--- tests/ert/ui_tests/cli/test_update.py | 2 +- tests/ert/ui_tests/gui/test_csv_export.py | 6 +-- .../config/config_dict_generator.py | 2 +- .../test_config_schema_deprecations.py | 2 +- .../config/test_create_forward_model_json.py | 4 +- .../ert/unit_tests/config/test_ert_config.py | 2 +- tests/ert/unit_tests/config/test_field.py | 3 +- .../unit_tests/config/test_forward_model.py | 6 +-- tests/ert/unit_tests/config/test_num_cpu.py | 3 +- .../unit_tests/config/test_observations.py | 3 +- .../config/test_parser_error_collection.py | 15 +++--- .../unit_tests/config/test_queue_config.py | 4 +- .../unit_tests/config/test_surface_config.py | 6 +-- .../ensemble_evaluator/test_monitor.py | 6 +-- .../test_file_reporter.py | 54 +++++++++---------- .../test_forward_model_step.py | 6 +-- .../resources/test_run_eclipse_simulator.py | 18 +++---- .../unit_tests/resources/test_templating.py | 6 +-- tests/ert/unit_tests/scheduler/bin/bhist.py | 2 +- tests/ert/unit_tests/scheduler/bin/squeue.py | 6 +-- tests/ert/unit_tests/scheduler/test_job.py | 6 +-- .../unit_tests/scheduler/test_lsf_driver.py | 20 +++---- .../scheduler/test_openpbs_driver.py | 8 +-- .../unit_tests/scheduler/test_slurm_driver.py | 14 ++--- .../unit_tests/services/test_base_service.py | 6 +-- .../unit_tests/storage/test_local_storage.py | 6 +-- .../ert/unit_tests/test_run_path_creation.py | 2 +- tests/everest/test_logging.py | 2 +- tests/everest/test_templating.py | 6 +-- 61 files changed, 168 insertions(+), 182 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3a4b4db4b21..a0e849e59f9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -11,7 +11,7 @@ repos: exclude: test-data/ert/eclipse/parse/ERROR.PRT # exact format is needed for testing - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.8.6 + rev: v0.9.1 hooks: - id: ruff args: [ --fix ] diff --git a/src/_ert/forward_model_runner/forward_model_step.py b/src/_ert/forward_model_runner/forward_model_step.py index 6a277247d59..b9350ce1b00 100644 --- a/src/_ert/forward_model_runner/forward_model_step.py +++ b/src/_ert/forward_model_runner/forward_model_step.py @@ -239,7 +239,7 @@ def _create_exited_message_based_on_exit_code( self.job_data["error_file"] ): return exited_message.with_error( - f'Found the error file:{self.job_data["error_file"]} - job failed.' + f"Found the error file:{self.job_data['error_file']} - job failed." ) if target_file_mtime: @@ -264,7 +264,7 @@ def _create_exited_msg_for_non_zero_exit_code( f"Forward model step {self.job_data.get('name')} " f"was killed due to out-of-memory on {socket.gethostname()}. " "Max memory usage recorded by Ert for the " - f"realization was {max_memory_usage//1024//1024} MB. " + f"realization was {max_memory_usage // 1024 // 1024} MB. " "Please add REALIZATION_MEMORY to your ert config together " "with a suitable memory amount to avoid this." ) @@ -322,12 +322,12 @@ def _check_job_files(self) -> list[str]: """ errors = [] if self.job_data.get("stdin") and not os.path.exists(self.job_data["stdin"]): - errors.append(f'Could not locate stdin file: {self.job_data["stdin"]}') + errors.append(f"Could not locate stdin file: {self.job_data['stdin']}") if self.job_data.get("start_file") and not os.path.exists( cast(Path, self.job_data["start_file"]) ): - errors.append(f'Could not locate start_file:{self.job_data["start_file"]}') + errors.append(f"Could not locate start_file:{self.job_data['start_file']}") if self.job_data.get("error_file") and os.path.exists( cast(Path, self.job_data.get("error_file")) diff --git a/src/ert/callbacks.py b/src/ert/callbacks.py index 8a464049b12..6d1c297162a 100644 --- a/src/ert/callbacks.py +++ b/src/ert/callbacks.py @@ -124,8 +124,7 @@ async def forward_model_ok( ) parameters_result = LoadResult( LoadStatus.LOAD_FAILURE, - "Failed to load results for realization " - f"{realization}, failed with: {err}", + f"Failed to load results for realization {realization}, failed with: {err}", ) final_result = parameters_result diff --git a/src/ert/config/ert_config.py b/src/ert/config/ert_config.py index 83800d5ce96..ec79c576ec1 100644 --- a/src/ert/config/ert_config.py +++ b/src/ert/config/ert_config.py @@ -823,7 +823,7 @@ def _create_list_of_forward_model_steps_to_run( ) except Exception as e: # type: ignore ConfigWarning.warn( - f"Unexpected plugin forward model exception: " f"{e!s}", + f"Unexpected plugin forward model exception: {e!s}", context=fm_step.name, ) diff --git a/src/ert/config/parsing/observations_parser.py b/src/ert/config/parsing/observations_parser.py index ee7388fd318..4363c3dcc88 100644 --- a/src/ert/config/parsing/observations_parser.py +++ b/src/ert/config/parsing/observations_parser.py @@ -415,8 +415,7 @@ def _validate_gen_obs_values( filename = os.path.join(directory, filename) if not os.path.exists(filename): raise ObservationConfigError.with_context( - "The following keywords did not" - f" resolve to a valid path:\n {key}", + f"The following keywords did not resolve to a valid path:\n {key}", value, ) setattr(output, str(key).lower(), filename) @@ -500,7 +499,7 @@ def _conversion_error( token: FileContextToken, value: Any, type_name: str ) -> ObservationConfigError: return ObservationConfigError.with_context( - f"Could not convert {value} to " f'{type_name}. Failed to validate "{value}"', + f'Could not convert {value} to {type_name}. Failed to validate "{value}"', token, ) diff --git a/src/ert/ensemble_evaluator/_ensemble.py b/src/ert/ensemble_evaluator/_ensemble.py index 05dcb38ecb1..c23d14ec796 100644 --- a/src/ert/ensemble_evaluator/_ensemble.py +++ b/src/ert/ensemble_evaluator/_ensemble.py @@ -291,7 +291,7 @@ async def _evaluate_inner( # pylint: disable=too-many-branches except Exception as exc: logger.exception( ( - "Unexpected exception in ensemble: \n" "".join( + "Unexpected exception in ensemble: \n".join( traceback.format_exception(None, exc, exc.__traceback__) ) ), diff --git a/src/ert/gui/ertwidgets/models/activerealizationsmodel.py b/src/ert/gui/ertwidgets/models/activerealizationsmodel.py index 79859cacc23..e5f5d804829 100644 --- a/src/ert/gui/ertwidgets/models/activerealizationsmodel.py +++ b/src/ert/gui/ertwidgets/models/activerealizationsmodel.py @@ -25,7 +25,7 @@ def setValueFromMask(self, mask: Collection[bool | int]) -> None: def getDefaultValue(self) -> str | None: if self.show_default: size = self.ensemble_size - return f"0-{size-1:d}" + return f"0-{size - 1:d}" return None def getActiveRealizationsMask(self) -> list[bool]: diff --git a/src/ert/gui/simulation/experiment_panel.py b/src/ert/gui/simulation/experiment_panel.py index 8ff43ed2cd9..b454d3448a8 100644 --- a/src/ert/gui/simulation/experiment_panel.py +++ b/src/ert/gui/simulation/experiment_panel.py @@ -298,7 +298,7 @@ def run_experiment(self) -> None: msg_box.setIcon(QMessageBox.Warning) msg_box.setText("ERT could not delete the existing runpath") msg_box.setInformativeText( - f"{e}\n\n" "Continue without deleting the runpath?" + f"{e}\n\nContinue without deleting the runpath?" ) msg_box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) msg_box.setDefaultButton(QMessageBox.No) diff --git a/src/ert/gui/simulation/view/progress_widget.py b/src/ert/gui/simulation/view/progress_widget.py index 395ddb77737..1a01fef930e 100644 --- a/src/ert/gui/simulation/view/progress_widget.py +++ b/src/ert/gui/simulation/view/progress_widget.py @@ -84,7 +84,7 @@ def repaint_components(self) -> None: for state, label in self._legend_map_text.items(): label.setText( - f" {state} ({self._status.get(state,0)}/{self._realization_count})" + f" {state} ({self._status.get(state, 0)}/{self._realization_count})" ) def stop_waiting_progress_bar(self) -> None: diff --git a/src/ert/gui/suggestor/_suggestor_message.py b/src/ert/gui/suggestor/_suggestor_message.py index cf2831b3dde..e786340a836 100644 --- a/src/ert/gui/suggestor/_suggestor_message.py +++ b/src/ert/gui/suggestor/_suggestor_message.py @@ -122,7 +122,7 @@ def _expanded_text(self) -> str: first = True for loc in self._locations: if first: - location_paragraphs += f'

{self._color_bold("location:")}{loc}

' + location_paragraphs += f"

{self._color_bold('location:')}{loc}

" first = False else: location_paragraphs += f"

{loc}

" diff --git a/src/ert/gui/tools/plot/customize/default_customization_view.py b/src/ert/gui/tools/plot/customize/default_customization_view.py index a03720f1f91..54694550edd 100644 --- a/src/ert/gui/tools/plot/customize/default_customization_view.py +++ b/src/ert/gui/tools/plot/customize/default_customization_view.py @@ -33,20 +33,20 @@ def __init__(self) -> None: self.addLineEdit( "title", "Title", - f'The title of the plot. {_label_msg("title")}', + f"The title of the plot. {_label_msg('title')}", placeholder="Title", ) self.addSpacing() self.addLineEdit( "x_label", "x-label", - f'The label of the x-axis. {_label_msg("label")}', + f"The label of the x-axis. {_label_msg('label')}", placeholder="x-label", ) self.addLineEdit( "y_label", "y-label", - f'The label of the y-axis. {_label_msg("label")}', + f"The label of the y-axis. {_label_msg('label')}", placeholder="y-label", ) self.addSpacing() diff --git a/src/ert/gui/tools/plot/plot_window.py b/src/ert/gui/tools/plot/plot_window.py index 1dc3b2fbbce..e19efb380ec 100644 --- a/src/ert/gui/tools/plot/plot_window.py +++ b/src/ert/gui/tools/plot/plot_window.py @@ -174,7 +174,7 @@ def __init__(self, config_file: str, parent: QWidget | None): self._data_type_keys_widget.selectDefault() - logger.info(f"PlotWindow __init__ done. time={time.perf_counter() -t}") + logger.info(f"PlotWindow __init__ done. time={time.perf_counter() - t}") @Slot(int) def currentTabChanged(self, index: int) -> None: diff --git a/src/ert/gui/tools/workflows/run_workflow_widget.py b/src/ert/gui/tools/workflows/run_workflow_widget.py index 99a122f2879..811d7b72a49 100644 --- a/src/ert/gui/tools/workflows/run_workflow_widget.py +++ b/src/ert/gui/tools/workflows/run_workflow_widget.py @@ -174,7 +174,7 @@ def workflowFinishedWithFail(self) -> None: (wfname, info) for wfname, info in report.items() if not info["completed"] ] - title_text = f"Workflow{'s' if len(failing_workflows) > 1 else ''} failed" + title_text = f"Workflow{'s' if len(failing_workflows) > 1 else ''} failed" content_text = "\n\n".join( [ f"{wfname} failed: \n {info['stderr'].strip()}" diff --git a/src/ert/plugins/hook_implementations/workflows/export_runpath.py b/src/ert/plugins/hook_implementations/workflows/export_runpath.py index 86c1ca6a31d..18e78be5f5e 100644 --- a/src/ert/plugins/hook_implementations/workflows/export_runpath.py +++ b/src/ert/plugins/hook_implementations/workflows/export_runpath.py @@ -75,7 +75,7 @@ def _get_rangestrings( ) -> tuple[str, str]: if not args: return ( - f"0-{number_of_realizations-1}", + f"0-{number_of_realizations - 1}", "0-0", # weird default behavior, kept for backwards compatability ) if "|" not in args: diff --git a/src/ert/plugins/hook_specifications/forward_model_steps.py b/src/ert/plugins/hook_specifications/forward_model_steps.py index 646add4fead..e25c7e94c24 100644 --- a/src/ert/plugins/hook_specifications/forward_model_steps.py +++ b/src/ert/plugins/hook_specifications/forward_model_steps.py @@ -11,9 +11,9 @@ @no_type_check @hook_specification -def installable_forward_model_steps() -> ( - PluginResponse[list[type[ForwardModelStepPlugin]]] -): +def installable_forward_model_steps() -> PluginResponse[ + list[type[ForwardModelStepPlugin]] +]: """ :return: List of forward model step plugins in the form of subclasses of the ForwardModelStepPlugin class diff --git a/src/ert/plugins/plugin_manager.py b/src/ert/plugins/plugin_manager.py index 0a4ce86dd19..1256e53c964 100644 --- a/src/ert/plugins/plugin_manager.py +++ b/src/ert/plugins/plugin_manager.py @@ -94,7 +94,7 @@ def _evaluate_config_hook(hook: pluggy.HookCaller, config_name: str) -> str | No logger.debug( f"Got {config_name} config path from " f"{response.plugin_metadata.plugin_name} " - f"({response.plugin_metadata.function_name,})" + f"({(response.plugin_metadata.function_name,)})" ) return response.data diff --git a/src/ert/plugins/plugin_response.py b/src/ert/plugins/plugin_response.py index cbedc28f1a9..f827067534e 100644 --- a/src/ert/plugins/plugin_response.py +++ b/src/ert/plugins/plugin_response.py @@ -1,14 +1,15 @@ from __future__ import annotations +from dataclasses import dataclass from typing import Generic, TypeVar T = TypeVar("T") +@dataclass class PluginMetadata: - def __init__(self, plugin_name: str, function_name: str) -> None: - self.plugin_name = plugin_name - self.function_name = function_name + plugin_name: str + function_name: str class PluginResponse(Generic[T]): diff --git a/src/ert/resources/shell_scripts/copy_directory.py b/src/ert/resources/shell_scripts/copy_directory.py index 7d2bc6b3a62..da27d47e1b3 100755 --- a/src/ert/resources/shell_scripts/copy_directory.py +++ b/src/ert/resources/shell_scripts/copy_directory.py @@ -34,8 +34,7 @@ def copy_directory(src_path: str, target_path: str) -> None: ) from err else: raise OSError( - f"Input argument: '{src_path}' " - "does not correspond to an existing directory" + f"Input argument: '{src_path}' does not correspond to an existing directory" ) diff --git a/src/ert/scheduler/job.py b/src/ert/scheduler/job.py index 83c8d79d29a..36ad286b69c 100644 --- a/src/ert/scheduler/job.py +++ b/src/ert/scheduler/job.py @@ -170,7 +170,7 @@ async def run( if attempt < max_submit - 1: message = ( f"Realization {self.iens} failed, " - f"resubmitting for attempt {attempt+2} of {max_submit}" + f"resubmitting for attempt {attempt + 2} of {max_submit}" ) logger.warning(message) self.returncode = asyncio.Future() diff --git a/src/ert/scheduler/openpbs_driver.py b/src/ert/scheduler/openpbs_driver.py index 0c4c0352017..c8a6287bf79 100644 --- a/src/ert/scheduler/openpbs_driver.py +++ b/src/ert/scheduler/openpbs_driver.py @@ -161,7 +161,7 @@ def _build_resource_string( if num_cpu > 1: cpu_resources += [f"ncpus={num_cpu}"] if realization_memory > 0: - cpu_resources += [f"mem={realization_memory // 1024**2 }mb"] + cpu_resources += [f"mem={realization_memory // 1024**2}mb"] if cpu_resources: resource_specifiers.append(":".join(cpu_resources)) diff --git a/src/ert/storage/local_storage.py b/src/ert/storage/local_storage.py index 7f75d449293..c8f9de3001b 100644 --- a/src/ert/storage/local_storage.py +++ b/src/ert/storage/local_storage.py @@ -479,12 +479,12 @@ def _migrate(self, version: int) -> None: Detected outdated storage (blockfs), which is no longer supported by ERT. Its contents are copied to: - {self.path / '_ert_block_storage_backup'} + {self.path / "_ert_block_storage_backup"} In order to migrate this storage, do the following: (1) with ert version <= 10.3.*, open up the same ert config with: - ENSPATH={self.path / '_ert_block_storage_backup'} + ENSPATH={self.path / "_ert_block_storage_backup"} (2) with current ert version, open up the same storage again. The contents of the storage should now be up-to-date, and you may @@ -503,7 +503,7 @@ def _migrate(self, version: int) -> None: enumerate([to2, to3, to4, to5, to6, to7, to8, to9], start=1) ) for from_version, migration in migrations[version - 1 :]: - print(f"* Updating storage to version: {from_version+1}") + print(f"* Updating storage to version: {from_version + 1}") migration.migrate(self.path) self._add_migration_information( from_version, from_version + 1, migration.info @@ -639,9 +639,9 @@ def local_storage_get_ert_config() -> ErtConfig: The ErtConfig instance. """ - assert ( - _migration_ert_config is not None - ), "Use 'local_storage_set_ert_config' before retrieving the config" + assert _migration_ert_config is not None, ( + "Use 'local_storage_set_ert_config' before retrieving the config" + ) return _migration_ert_config diff --git a/src/ert/storage/migration/to7.py b/src/ert/storage/migration/to7.py index c1036d0f71a..4e5e81576f5 100644 --- a/src/ert/storage/migration/to7.py +++ b/src/ert/storage/migration/to7.py @@ -91,9 +91,9 @@ def _migrate_response_datasets(path: Path) -> None: with open(responses_file, encoding="utf-8") as f: responses_obj = json.load(f) - assert ( - responses_obj is not None - ), f"Failed to load responses.json @ {responses_file}" + assert responses_obj is not None, ( + f"Failed to load responses.json @ {responses_file}" + ) gendata_keys = responses_obj.get("gen_data", {}).get("keys", []) diff --git a/src/ert/validation/rangestring.py b/src/ert/validation/rangestring.py index c67337fe0f8..4c197db5001 100644 --- a/src/ert/validation/rangestring.py +++ b/src/ert/validation/rangestring.py @@ -30,7 +30,7 @@ def store_range(begin: int, end: int) -> None: if end - begin == 1: ranges.append(f"{begin}") else: - ranges.append(f"{begin}-{end-1}") + ranges.append(f"{begin}-{end - 1}") start: int | None = None for i, is_active in enumerate(mask): diff --git a/src/everest/config/control_config.py b/src/everest/config/control_config.py index 689b5cb3508..fc924cfac5b 100644 --- a/src/everest/config/control_config.py +++ b/src/everest/config/control_config.py @@ -33,8 +33,7 @@ def _all_or_no_index(variables: ControlVariable) -> ControlVariable: if len({getattr(variable, "index", None) is None for variable in variables}) != 1: raise ValueError( - "Index should be given either for all of the variables or for none" - " of them" + "Index should be given either for all of the variables or for none of them" ) return variables diff --git a/src/everest/config/everest_config.py b/src/everest/config/everest_config.py index 9892dc1937f..451f0d46d58 100644 --- a/src/everest/config/everest_config.py +++ b/src/everest/config/everest_config.py @@ -801,13 +801,11 @@ def load_file_with_argparser( parser.error(f"File not found: {config_path}") except YAMLError as e: parser.error( - f"The config file: <{config_path}> contains" - f" invalid YAML syntax: {e!s}" + f"The config file: <{config_path}> contains invalid YAML syntax: {e!s}" ) except EverestValidationError as e: parser.error( - f"Loading config file <{config_path}> failed with:\n" - f"{format_errors(e)}" + f"Loading config file <{config_path}> failed with:\n{format_errors(e)}" ) def dump(self, fname: str | None = None) -> str | None: diff --git a/src/everest/export.py b/src/everest/export.py index ac49b082d92..318a2cef54c 100644 --- a/src/everest/export.py +++ b/src/everest/export.py @@ -194,15 +194,14 @@ def check_for_errors( if config.batches == []: export_errors.append( - "No batches selected for export. " - "Only optimization data will be exported." + "No batches selected for export. Only optimization data will be exported." ) return export_errors, False if not data_file_path: export_ecl = False export_errors.append( - "No data file found in config." "Only optimization data will be exported." + "No data file found in config.Only optimization data will be exported." ) # If no user defined keywords are present it is no longer possible to check diff --git a/src/everest/jobs/well_tools/__init__.py b/src/everest/jobs/well_tools/__init__.py index 6a93f6445bb..a0795ce6232 100644 --- a/src/everest/jobs/well_tools/__init__.py +++ b/src/everest/jobs/well_tools/__init__.py @@ -48,7 +48,7 @@ def well_set(well_data_file, new_entry_file, output_file): new_entry = everest.jobs.io.load_data(new_entry_file) if len(new_entry) != 1: - err_msg = "Expected there to be exactly one new entry " "in {nef}, was {ne}" + err_msg = "Expected there to be exactly one new entry in {nef}, was {ne}" raise ValueError(err_msg.format(nef=new_entry_file, ne=len(new_entry))) entry_key = next(iter(new_entry.keys())) diff --git a/src/everest/simulator/__init__.py b/src/everest/simulator/__init__.py index b1611081e43..901ab28446c 100644 --- a/src/everest/simulator/__init__.py +++ b/src/everest/simulator/__init__.py @@ -4,7 +4,7 @@ JOB_FAILURE = "Failed" -DEFAULT_DATA_SUMMARY_KEYS = ("YEAR", "YEARS" "TCPU", "TCPUDAY", "MONTH", "DAY") +DEFAULT_DATA_SUMMARY_KEYS = ("YEAR", "YEARSTCPU", "TCPUDAY", "MONTH", "DAY") DEFAULT_FIELD_SUMMARY_KEYS = ( diff --git a/test-data/ert/poly_example/Plot_correlations.ipynb b/test-data/ert/poly_example/Plot_correlations.ipynb index d85d8613dcb..13877d38dda 100644 --- a/test-data/ert/poly_example/Plot_correlations.ipynb +++ b/test-data/ert/poly_example/Plot_correlations.ipynb @@ -41,7 +41,7 @@ "plt.xlabel(\"Response\")\n", "plt.ylabel(\"Parameter\")\n", "plt.xticks(\n", - " range(coeffs.shape[1]), labels=[f\"Response {i+1}\" for i in range(coeffs.shape[1])]\n", + " range(coeffs.shape[1]), labels=[f\"Response {i + 1}\" for i in range(coeffs.shape[1])]\n", ")\n", "plt.yticks(range(coeffs.shape[0]), labels=parameter_names)\n", "\n", diff --git a/test-data/ert/snake_oil/forward_models/snake_oil_diff.py b/test-data/ert/snake_oil/forward_models/snake_oil_diff.py index a08fcf2be3f..5e78b6d2478 100755 --- a/test-data/ert/snake_oil/forward_models/snake_oil_diff.py +++ b/test-data/ert/snake_oil/forward_models/snake_oil_diff.py @@ -5,7 +5,7 @@ def writeDiff(filename, vector1, vector2): with open(filename, "w", encoding="utf-8") as f: for node1, node2 in zip(vector1, vector2, strict=False): - f.write(f"{node1-node2:f}\n") + f.write(f"{node1 - node2:f}\n") if __name__ == "__main__": diff --git a/tests/ert/conftest.py b/tests/ert/conftest.py index 39502e495a3..4d88997b348 100644 --- a/tests/ert/conftest.py +++ b/tests/ert/conftest.py @@ -43,9 +43,9 @@ def log_check(): yield logger_after = logging.getLogger() level_after = logger_after.getEffectiveLevel() - assert ( - level_after == logging.WARNING - ), f"Detected differences in log environment: Changed to {level_after}" + assert level_after == logging.WARNING, ( + f"Detected differences in log environment: Changed to {level_after}" + ) @pytest.fixture(scope="session", autouse=True) diff --git a/tests/ert/ui_tests/cli/analysis/test_adaptive_localization.py b/tests/ert/ui_tests/cli/analysis/test_adaptive_localization.py index c97ecbfa0a1..7c4c6f6c891 100644 --- a/tests/ert/ui_tests/cli/analysis/test_adaptive_localization.py +++ b/tests/ert/ui_tests/cli/analysis/test_adaptive_localization.py @@ -320,9 +320,9 @@ def test_that_posterior_generalized_variance_increases_in_cutoff(): # Check that posterior generalized variance in positive, increases in cutoff and # does not exceed prior generalized variance assert generalized_variance_1 > 0, f"Assertion failed with cutoff1={cutoff1}" - assert ( - generalized_variance_1 <= generalized_variance_2 - ), f"Assertion failed with cutoff1={cutoff1} and cutoff2={cutoff2}" - assert ( - generalized_variance_2 <= generalized_variance_prior - ), f"Assertion failed with cutoff2={cutoff2}" + assert generalized_variance_1 <= generalized_variance_2, ( + f"Assertion failed with cutoff1={cutoff1} and cutoff2={cutoff2}" + ) + assert generalized_variance_2 <= generalized_variance_prior, ( + f"Assertion failed with cutoff2={cutoff2}" + ) diff --git a/tests/ert/ui_tests/cli/test_update.py b/tests/ert/ui_tests/cli/test_update.py index 461b268c8d5..74313a3fec9 100644 --- a/tests/ert/ui_tests/cli/test_update.py +++ b/tests/ert/ui_tests/cli/test_update.py @@ -167,7 +167,7 @@ def test_update_lowers_generalized_variance_or_deactives_observations( os.chmod(py, mode.st_mode | stat.S_IEXEC) for i in range(num_groups): - print(f"{i * per_group } {(i + 1) * per_group}") + print(f"{i * per_group} {(i + 1) * per_group}") with open("observations", mode="a", encoding="utf-8") as f: f.write(observation.format(i=i)) Path(f"poly_obs_{i}.txt").write_text( diff --git a/tests/ert/ui_tests/gui/test_csv_export.py b/tests/ert/ui_tests/gui/test_csv_export.py index 7d53cd9a0a5..9452c236b86 100644 --- a/tests/ert/ui_tests/gui/test_csv_export.py +++ b/tests/ert/ui_tests/gui/test_csv_export.py @@ -144,6 +144,6 @@ def test_that_export_tool_does_not_produce_duplicate_data( second_half = df.iloc[half_point:] # Ensure the two halves are not identical - assert not first_half.equals( - second_half - ), "The first half of the data is identical to the second half." + assert not first_half.equals(second_half), ( + "The first half of the data is identical to the second half." + ) diff --git a/tests/ert/unit_tests/config/config_dict_generator.py b/tests/ert/unit_tests/config/config_dict_generator.py index 39945694396..82b85e9a4fa 100644 --- a/tests/ert/unit_tests/config/config_dict_generator.py +++ b/tests/ert/unit_tests/config/config_dict_generator.py @@ -713,7 +713,7 @@ def to_config_file(filename, config_values): for job_name, job_args in keyword_value: config.write( f"{keyword} {job_name}" - f"({', '.join(f'{a}={b}' for a,b in job_args)})\n" + f"({', '.join(f'{a}={b}' for a, b in job_args)})\n" ) elif keyword == ConfigKeys.FIELD: # keyword_value is a list of dicts, each defining a field diff --git a/tests/ert/unit_tests/config/parsing/test_config_schema_deprecations.py b/tests/ert/unit_tests/config/parsing/test_config_schema_deprecations.py index 82b4baf7651..4d4164420cc 100644 --- a/tests/ert/unit_tests/config/parsing/test_config_schema_deprecations.py +++ b/tests/ert/unit_tests/config/parsing/test_config_schema_deprecations.py @@ -178,7 +178,7 @@ def test_suggester_gives_deprecated_define_migration_hint( tmp_path, definer, definition, expected ): (tmp_path / "config.ert").write_text( - "NUM_REALIZATIONS 1\n" f"{definer} {definition}\n" + f"NUM_REALIZATIONS 1\n{definer} {definition}\n" ) print(f"{definer} {definition}") if expected: diff --git a/tests/ert/unit_tests/config/test_create_forward_model_json.py b/tests/ert/unit_tests/config/test_create_forward_model_json.py index 43a87f3c7be..fcc4a336f0d 100644 --- a/tests/ert/unit_tests/config/test_create_forward_model_json.py +++ b/tests/ert/unit_tests/config/test_create_forward_model_json.py @@ -174,11 +174,11 @@ def create_std_file(config, std="stdout", step_index=None): if config[std]: return f"{config[std]}" else: - return f'{config["name"]}.{std}' + return f"{config['name']}.{std}" elif config[std]: return f"{config[std]}.{step_index}" else: - return f'{config["name"]}.{std}.{step_index}' + return f"{config['name']}.{std}.{step_index}" def validate_forward_model(forward_model, forward_model_config): diff --git a/tests/ert/unit_tests/config/test_ert_config.py b/tests/ert/unit_tests/config/test_ert_config.py index 637db1d8484..0c88a8f1e94 100644 --- a/tests/ert/unit_tests/config/test_ert_config.py +++ b/tests/ert/unit_tests/config/test_ert_config.py @@ -588,7 +588,7 @@ def test_that_empty_job_directory_gives_warning(tmp_path): dedent( f""" NUM_REALIZATIONS 1 - INSTALL_JOB_DIRECTORY {tmp_path / 'empty'} + INSTALL_JOB_DIRECTORY {tmp_path / "empty"} """ ) ) diff --git a/tests/ert/unit_tests/config/test_field.py b/tests/ert/unit_tests/config/test_field.py index 9dea78de7e6..af99a75cd94 100644 --- a/tests/ert/unit_tests/config/test_field.py +++ b/tests/ert/unit_tests/config/test_field.py @@ -189,8 +189,7 @@ def test_missing_init_files_gives_a_user_error_message(parse_field_line): def test_the_user_gets_a_warning_about_input_transform_usage(parse_field_line): with pytest.warns( ConfigWarning, - match="Got INPUT_TRANSFORM for FIELD: f," - " this has no effect and can be removed", + match="Got INPUT_TRANSFORM for FIELD: f, this has no effect and can be removed", ): _ = parse_field_line( "FIELD f parameter out.roff INPUT_TRANSFORM:log INIT_FILES:file.init" diff --git a/tests/ert/unit_tests/config/test_forward_model.py b/tests/ert/unit_tests/config/test_forward_model.py index 78ef78cc4e0..a76e54f7808 100644 --- a/tests/ert/unit_tests/config/test_forward_model.py +++ b/tests/ert/unit_tests/config/test_forward_model.py @@ -657,9 +657,9 @@ def validate_pre_realization_run( } for a, v in expected_attrs.items(): - assert ( - getattr(first_fm, a) == v - ), f"Expected fm[{a}] to be {v} but was {getattr(first_fm,a)}" + assert getattr(first_fm, a) == v, ( + f"Expected fm[{a}] to be {v} but was {getattr(first_fm, a)}" + ) fm_json = create_forward_model_json( context=ert_config.substitutions, diff --git a/tests/ert/unit_tests/config/test_num_cpu.py b/tests/ert/unit_tests/config/test_num_cpu.py index 03862ec767b..65221c4d71c 100644 --- a/tests/ert/unit_tests/config/test_num_cpu.py +++ b/tests/ert/unit_tests/config/test_num_cpu.py @@ -120,6 +120,5 @@ def test_num_cpu_from_data_file_used_if_config_num_cpu_not_set( def test_wrong_num_cpu_raises_validation_error(num_cpu_value, error_msg): with pytest.raises(ConfigValidationError, match=error_msg): ErtConfig.from_file_contents( - f"{ConfigKeys.NUM_REALIZATIONS} 1\n" - f"{ConfigKeys.NUM_CPU} {num_cpu_value}\n" + f"{ConfigKeys.NUM_REALIZATIONS} 1\n{ConfigKeys.NUM_CPU} {num_cpu_value}\n" ) diff --git a/tests/ert/unit_tests/config/test_observations.py b/tests/ert/unit_tests/config/test_observations.py index 5b81dcd9d1d..bc7b0bd14ba 100644 --- a/tests/ert/unit_tests/config/test_observations.py +++ b/tests/ert/unit_tests/config/test_observations.py @@ -120,8 +120,7 @@ def test_that_using_summary_observations_without_eclbase_shows_user_error(): """ ) Path("observations_config").write_text( - "SUMMARY_OBSERVATION FOPR_1 " - "{ KEY=FOPR; VALUE=1; ERROR=1; DATE=2023-03-15; };", + "SUMMARY_OBSERVATION FOPR_1 { KEY=FOPR; VALUE=1; ERROR=1; DATE=2023-03-15; };", encoding="utf-8", ) Path("config.ert").write_text(config_text, encoding="utf-8") diff --git a/tests/ert/unit_tests/config/test_parser_error_collection.py b/tests/ert/unit_tests/config/test_parser_error_collection.py index 0d76bf9d0c3..5b0b84e8492 100644 --- a/tests/ert/unit_tests/config/test_parser_error_collection.py +++ b/tests/ert/unit_tests/config/test_parser_error_collection.py @@ -60,8 +60,7 @@ def find_and_assert_errors_matching_filename( ) assert len(matching_errors) > 0, ( - f"Expected minimum 1 error matching filename" - f" {filename}, got 0 from {errors}" + f"Expected minimum 1 error matching filename {filename}, got 0 from {errors}" ) return matching_errors @@ -106,9 +105,9 @@ def find_and_assert_errors_matching_message( re_match = re.compile(match) matching_errors = [err for err in errors if re.search(re_match, err.message)] - assert ( - len(matching_errors) > 0 - ), f"Expected to find error matching message {match} {errors}" + assert len(matching_errors) > 0, ( + f"Expected to find error matching message {match} {errors}" + ) return matching_errors @@ -624,7 +623,7 @@ def test_that_cyclical_import_error_is_located_stop_early(n): contents=dedent( f""" JOBNAME include{i} - INCLUDE include{i+1}.ert + INCLUDE include{i + 1}.ert """ ) ) @@ -632,7 +631,7 @@ def test_that_cyclical_import_error_is_located_stop_early(n): } expected_match = ( - f"test.ert->{'->'.join([f'include{i}.ert' for i in range(n+1)])}->test.ert" + f"test.ert->{'->'.join([f'include{i}.ert' for i in range(n + 1)])}->test.ert" ) expected_error = ExpectedErrorInfo( @@ -641,7 +640,7 @@ def test_that_cyclical_import_error_is_located_stop_early(n): f"include{n}.ert": FileDetail( contents=dedent( f""" - JOBNAME include{n+1} + JOBNAME include{n + 1} INCLUDE test.ert """ ) diff --git a/tests/ert/unit_tests/config/test_queue_config.py b/tests/ert/unit_tests/config/test_queue_config.py index 9f2105182a8..75e0b460813 100644 --- a/tests/ert/unit_tests/config/test_queue_config.py +++ b/tests/ert/unit_tests/config/test_queue_config.py @@ -276,7 +276,7 @@ def test_multiple_max_submit_keywords(): def test_wrong_max_submit_raises_validation_error(max_submit_value, error_msg): with pytest.raises(ConfigValidationError, match=error_msg): ErtConfig.from_file_contents( - "NUM_REALIZATIONS 1\n" f"MAX_SUBMIT {max_submit_value}\n" + f"NUM_REALIZATIONS 1\nMAX_SUBMIT {max_submit_value}\n" ) @@ -375,7 +375,7 @@ def test_wrong_generic_queue_option_raises_validation_error(queue_system, key, v ) with pytest.raises(ConfigValidationError, match=error_msg): ErtConfig.from_file_contents( - "NUM_REALIZATIONS 1\n" f"QUEUE_SYSTEM {queue_system}\n" f"{key} {value}\n" + f"NUM_REALIZATIONS 1\nQUEUE_SYSTEM {queue_system}\n{key} {value}\n" ) diff --git a/tests/ert/unit_tests/config/test_surface_config.py b/tests/ert/unit_tests/config/test_surface_config.py index 3435d2a21cd..52fb2a011ae 100644 --- a/tests/ert/unit_tests/config/test_surface_config.py +++ b/tests/ert/unit_tests/config/test_surface_config.py @@ -75,9 +75,9 @@ def test_runpath_roundtrip(tmp_path, storage, surface): ("yflip", 1.0), ("rotation", 10), ): - assert ( - getattr(config, prop) == getattr(actual_surface, prop) == val - ), f"Failed for: {prop}" + assert getattr(config, prop) == getattr(actual_surface, prop) == val, ( + f"Failed for: {prop}" + ) def test_init_files_must_contain_placeholder_when_not_forward_init(): diff --git a/tests/ert/unit_tests/ensemble_evaluator/test_monitor.py b/tests/ert/unit_tests/ensemble_evaluator/test_monitor.py index a8d762ce59c..41548e725d7 100644 --- a/tests/ert/unit_tests/ensemble_evaluator/test_monitor.py +++ b/tests/ert/unit_tests/ensemble_evaluator/test_monitor.py @@ -155,9 +155,9 @@ async def mock_event_handler(router_socket): async for event in monitor.track(): raise RuntimeError(f"Got unexpected event {event} after cancellation") - assert ( - "Evaluator did not send the TERMINATED event!" - ) in caplog.messages, "Monitor receiver did not stop!" + assert ("Evaluator did not send the TERMINATED event!") in caplog.messages, ( + "Monitor receiver did not stop!" + ) await websocket_server_task diff --git a/tests/ert/unit_tests/forward_model_runner/test_file_reporter.py b/tests/ert/unit_tests/forward_model_runner/test_file_reporter.py index a4db3e1fb25..bdd37ff3cb5 100644 --- a/tests/ert/unit_tests/forward_model_runner/test_file_reporter.py +++ b/tests/ert/unit_tests/forward_model_runner/test_file_reporter.py @@ -59,9 +59,9 @@ def test_report_with_successful_start_message_argument(reporter): with open(STATUS_file, encoding="utf-8") as f: assert "fmstep1" in f.readline(), "STATUS file missing fmstep1" with open(LOG_file, encoding="utf-8") as f: - assert ( - "Calling: /bin/sh --foo 1 --bar 2" in f.readline() - ), """JOB_LOG file missing executable and arguments""" + assert "Calling: /bin/sh --foo 1 --bar 2" in f.readline(), ( + """JOB_LOG file missing executable and arguments""" + ) with open(STATUS_json, encoding="utf-8") as f: content = "".join(f.readlines()) @@ -77,18 +77,18 @@ def test_report_with_failed_start_message_argument(reporter): reporter.report(msg) with open(STATUS_file, encoding="utf-8") as f: - assert ( - "EXIT: -10/massive_failure" in f.readline() - ), "STATUS file missing EXIT message" + assert "EXIT: -10/massive_failure" in f.readline(), ( + "STATUS file missing EXIT message" + ) with open(STATUS_json, encoding="utf-8") as f: content = "".join(f.readlines()) assert '"status": "Failure"' in content, "status.json missing Failure status" - assert ( - '"error": "massive_failure"' in content - ), "status.json missing error message" - assert ( - reporter.status_dict["jobs"][0]["end_time"] is not None - ), "end_time not set for fmstep1" + assert '"error": "massive_failure"' in content, ( + "status.json missing error message" + ) + assert reporter.status_dict["jobs"][0]["end_time"] is not None, ( + "end_time not set for fmstep1" + ) @pytest.mark.usefixtures("use_tmpdir") @@ -117,18 +117,18 @@ def test_report_with_failed_exit_message_argument(reporter): with open(ERROR_file, encoding="utf-8") as f: content = "".join(f.readlines()) assert "fmstep1" in content, "ERROR file missing fmstep" - assert ( - "massive_failure" in content - ), "ERROR file missing reason" - assert ( - "stderr: Not redirected" in content - ), "ERROR had invalid stderr information" + assert "massive_failure" in content, ( + "ERROR file missing reason" + ) + assert "stderr: Not redirected" in content, ( + "ERROR had invalid stderr information" + ) with open(STATUS_json, encoding="utf-8") as f: content = "".join(f.readlines()) assert '"status": "Failure"' in content, "status.json missing Failure status" - assert ( - '"error": "massive_failure"' in content - ), "status.json missing error message" + assert '"error": "massive_failure"' in content, ( + "status.json missing error message" + ) assert reporter.status_dict["jobs"][0]["end_time"] is not None @@ -145,12 +145,12 @@ def test_report_with_running_message_argument(reporter): with open(STATUS_json, encoding="utf-8") as f: content = "".join(f.readlines()) assert '"status": "Running"' in content, "status.json missing status" - assert ( - '"max_memory_usage": 100' in content - ), "status.json missing max_memory_usage" - assert ( - '"current_memory_usage": 10' in content - ), "status.json missing current_memory_usage" + assert '"max_memory_usage": 100' in content, ( + "status.json missing max_memory_usage" + ) + assert '"current_memory_usage": 10' in content, ( + "status.json missing current_memory_usage" + ) assert '"cpu_seconds": 1.1' in content, "status.json missing cpu_seconds" diff --git a/tests/ert/unit_tests/forward_model_runner/test_forward_model_step.py b/tests/ert/unit_tests/forward_model_runner/test_forward_model_step.py index 6b93c2ecf02..6e624a91234 100644 --- a/tests/ert/unit_tests/forward_model_runner/test_forward_model_step.py +++ b/tests/ert/unit_tests/forward_model_runner/test_forward_model_step.py @@ -211,9 +211,9 @@ def test_run_fails_using_exit_bash_builtin(): assert len(statuses) == 3, "Wrong statuses count" assert statuses[2].exit_code == 1, "Exited status wrong exit_code" - assert ( - statuses[2].error_message == "Process exited with status code 1" - ), "Exited status wrong error_message" + assert statuses[2].error_message == "Process exited with status code 1", ( + "Exited status wrong error_message" + ) @pytest.mark.usefixtures("use_tmpdir") diff --git a/tests/ert/unit_tests/resources/test_run_eclipse_simulator.py b/tests/ert/unit_tests/resources/test_run_eclipse_simulator.py index 63a1e57a11d..9ff1e05483b 100644 --- a/tests/ert/unit_tests/resources/test_run_eclipse_simulator.py +++ b/tests/ert/unit_tests/resources/test_run_eclipse_simulator.py @@ -63,9 +63,9 @@ def test_run_eclipseX00_can_run_eclipse_and_verify(source_root): assert len(erun.parse_errors()) == 0 - assert not Path( - "EIGHTCELLS.h5" - ).exists(), "HDF conversion should not be run by default" + assert not Path("EIGHTCELLS.h5").exists(), ( + "HDF conversion should not be run by default" + ) @pytest.mark.integration_test @@ -197,9 +197,9 @@ def test_await_completed_summary_file_does_not_time_out_on_nosim_with_mpi(source ["eclipse", "SPE1.DATA", "--version", "2019.3", "--num-cpu=2"] ) assert Path("SPE1.OK").exists() - assert not Path( - "SPE1.UNSMRY" - ).exists(), "A nosim run should not produce an unsmry file" + assert not Path("SPE1.UNSMRY").exists(), ( + "A nosim run should not produce an unsmry file" + ) # The timeout will not happen since find_unsmry() returns None. # There is no assert on runtime because we cannot predict how long the Eclipse license @@ -309,9 +309,9 @@ def test_mpi_is_working_without_run_reservoirsimulator_knowing_it(source_root): assert Path("SPE1_PARALLEL.PRT").stat().st_size > 0, "Eclipse did not run at all" assert Path("SPE1_PARALLEL.MSG").exists(), "No output from MPI process 1" assert Path("SPE1_PARALLEL.2.MSG").exists(), "No output from MPI process 2" - assert not Path( - "SPE1_PARALLEL.3.MSG" - ).exists(), "There should not be 3 MPI processes" + assert not Path("SPE1_PARALLEL.3.MSG").exists(), ( + "There should not be 3 MPI processes" + ) @pytest.mark.parametrize( diff --git a/tests/ert/unit_tests/resources/test_templating.py b/tests/ert/unit_tests/resources/test_templating.py index c65868dd195..3e5d32b5166 100644 --- a/tests/ert/unit_tests/resources/test_templating.py +++ b/tests/ert/unit_tests/resources/test_templating.py @@ -214,11 +214,7 @@ def test_template_executable(): } json_file.write(json.dumps(parameters)) - params = ( - " --output_file out_file " - "--template_file template " - "--input_files other.json" - ) + params = " --output_file out_file --template_file template --input_files other.json" template_render_exec = str( Path(importlib.util.find_spec("ert").origin).parent / "resources/forward_models/template_render.py" diff --git a/tests/ert/unit_tests/scheduler/bin/bhist.py b/tests/ert/unit_tests/scheduler/bin/bhist.py index 9016be99fde..d92d9a599f5 100644 --- a/tests/ert/unit_tests/scheduler/bin/bhist.py +++ b/tests/ert/unit_tests/scheduler/bin/bhist.py @@ -69,7 +69,7 @@ def bhist_long_formatter(jobstats: list[Job]) -> str: f"{job.total!s:8.8s}" ) formatted_job_outputs.append(job_output) - return f"{50*'-'}".join(formatted_job_outputs) + return f"{50 * '-'}".join(formatted_job_outputs) def read(path: Path, default: str | None = None) -> str | None: diff --git a/tests/ert/unit_tests/scheduler/bin/squeue.py b/tests/ert/unit_tests/scheduler/bin/squeue.py index b4be01ab0b1..1c640f47c43 100644 --- a/tests/ert/unit_tests/scheduler/bin/squeue.py +++ b/tests/ert/unit_tests/scheduler/bin/squeue.py @@ -35,9 +35,9 @@ def main() -> None: args = get_parser().parse_args() assert args.noheader, "Mocked squeue requires noheader" - assert ( - args.format == "%i %T" - ), "Sorry, mocked squeue only supports one custom format." + assert args.format == "%i %T", ( + "Sorry, mocked squeue only supports one custom format." + ) jobs_path = Path(os.getenv("PYTEST_TMP_PATH", ".")) / "mock_jobs" diff --git a/tests/ert/unit_tests/scheduler/test_job.py b/tests/ert/unit_tests/scheduler/test_job.py index 029a74cc491..66cbd14b2d9 100644 --- a/tests/ert/unit_tests/scheduler/test_job.py +++ b/tests/ert/unit_tests/scheduler/test_job.py @@ -58,9 +58,9 @@ async def assert_scheduler_events( scheduler: Scheduler, expected_job_events: list[JobState] ) -> None: for expected_job_event in expected_job_events: - assert ( - scheduler._events.qsize() - ), f"Expected to find {expected_job_event=} in the event queue" + assert scheduler._events.qsize(), ( + f"Expected to find {expected_job_event=} in the event queue" + ) event = scheduler._events.get_nowait() assert event.queue_event_type == expected_job_event diff --git a/tests/ert/unit_tests/scheduler/test_lsf_driver.py b/tests/ert/unit_tests/scheduler/test_lsf_driver.py index 7064748a99b..61b8b4c0364 100644 --- a/tests/ert/unit_tests/scheduler/test_lsf_driver.py +++ b/tests/ert/unit_tests/scheduler/test_lsf_driver.py @@ -1007,7 +1007,7 @@ def not_found_bjobs(monkeypatch, tmp_path): monkeypatch.setenv("PATH", f"{bin_path}:{os.environ['PATH']}") bjobs_path = bin_path / "bjobs" bjobs_path.write_text( - "#!/bin/sh\n" 'echo "Job <$1> is not found"', + '#!/bin/sh\necho "Job <$1> is not found"', encoding="utf-8", ) bjobs_path.chmod(bjobs_path.stat().st_mode | stat.S_IEXEC) @@ -1034,9 +1034,9 @@ async def test_lsf_stdout_file(tmp_path, job_name): await driver.submit(0, "sh", "-c", "echo yay", name=job_name) await poll(driver, {0}) lsf_stdout = Path(f"{job_name}.LSF-stdout").read_text(encoding="utf-8") - assert Path( - f"{job_name}.LSF-stdout" - ).exists(), "LSF system did not write output file" + assert Path(f"{job_name}.LSF-stdout").exists(), ( + "LSF system did not write output file" + ) assert "Sender: " in lsf_stdout, "LSF stdout should always start with 'Sender:'" assert "The output (if any) follows:" in lsf_stdout @@ -1049,9 +1049,9 @@ async def test_lsf_dumps_stderr_to_file(tmp_path, job_name): failure_message = "failURE" await driver.submit(0, "sh", "-c", f"echo {failure_message} >&2", name=job_name) await poll(driver, {0}) - assert Path( - f"{job_name}.LSF-stderr" - ).exists(), "LSF system did not write stderr file" + assert Path(f"{job_name}.LSF-stderr").exists(), ( + "LSF system did not write stderr file" + ) assert ( Path(f"{job_name}.LSF-stderr").read_text(encoding="utf-8").strip() @@ -1196,9 +1196,9 @@ async def test_submit_with_num_cpu(pytestconfig, job_name): stdout, stderr = await process.communicate() stdout_no_whitespaces = re.sub(r"\s+", "", stdout.decode()) matches = re.search(r".*([0-9]+)ProcessorsRequested.*", stdout_no_whitespaces) - assert matches and matches[1] == str( - num_cpu - ), f"Could not verify processor allocation from stdout: {stdout}, stderr: {stderr}" + assert matches and matches[1] == str(num_cpu), ( + f"Could not verify processor allocation from stdout: {stdout}, stderr: {stderr}" + ) assert Path("test").read_text(encoding="utf-8") == "test\n" diff --git a/tests/ert/unit_tests/scheduler/test_openpbs_driver.py b/tests/ert/unit_tests/scheduler/test_openpbs_driver.py index 1a01609279f..cb39f0046a3 100644 --- a/tests/ert/unit_tests/scheduler/test_openpbs_driver.py +++ b/tests/ert/unit_tests/scheduler/test_openpbs_driver.py @@ -274,7 +274,7 @@ async def test_full_resource_string(realization_memory, num_cpu, cluster_label): Path("captured_qsub_args").read_text(encoding="utf-8") ) assert resources.get("mem", "") == ( - f"{realization_memory // 1024**2 }mb" if realization_memory > 0 else "" + f"{realization_memory // 1024**2}mb" if realization_memory > 0 else "" ) assert resources.get("select", "1") == "1" assert resources.get("ncpus", "1") == str(num_cpu) @@ -490,9 +490,9 @@ async def test_that_openpbs_driver_ignores_qstat_flakiness( with contextlib.suppress(TypeError): await asyncio.wait_for(poll(driver, expected={0}), timeout=10) - assert ( - int(Path("counter_file").read_text(encoding="utf-8")) >= 3 - ), "polling did not occur, test setup failed" + assert int(Path("counter_file").read_text(encoding="utf-8")) >= 3, ( + "polling did not occur, test setup failed" + ) assert text_to_ignore not in capsys.readouterr().out assert text_to_ignore not in capsys.readouterr().err diff --git a/tests/ert/unit_tests/scheduler/test_slurm_driver.py b/tests/ert/unit_tests/scheduler/test_slurm_driver.py index 16c6dfb783a..60cec0faeea 100644 --- a/tests/ert/unit_tests/scheduler/test_slurm_driver.py +++ b/tests/ert/unit_tests/scheduler/test_slurm_driver.py @@ -33,7 +33,7 @@ def capturing_sbatch(monkeypatch, tmp_path): monkeypatch.setenv("PATH", f"{bin_path}:{os.environ['PATH']}") sbatch_path = bin_path / "sbatch" sbatch_path.write_text( - "#!/bin/sh\n" "echo $@ > captured_sbatch_args\n" "echo 1", + "#!/bin/sh\necho $@ > captured_sbatch_args\necho 1", encoding="utf-8", ) sbatch_path.chmod(sbatch_path.stat().st_mode | stat.S_IEXEC) @@ -360,9 +360,9 @@ async def test_submit_with_num_cpu(pytestconfig, job_name): stderr=asyncio.subprocess.PIPE, ) stdout, stderr = await process.communicate() - assert " NumCPUs=2 " in stdout.decode( - errors="ignore" - ), f"Could not verify processor allocation from stdout: {stdout}, stderr: {stderr}" + assert " NumCPUs=2 " in stdout.decode(errors="ignore"), ( + f"Could not verify processor allocation from stdout: {stdout}, stderr: {stderr}" + ) assert Path("test").read_text(encoding="utf-8") == "test\n" @@ -427,9 +427,9 @@ async def finished(iens: int, returncode: int): # there. assert test_grace_time > job_kill_window, "Wrong test setup" await asyncio.sleep(test_grace_time) - assert not Path( - "survived" - ).exists(), "The process children of the job should also have been killed" + assert not Path("survived").exists(), ( + "The process children of the job should also have been killed" + ) @pytest.mark.parametrize("cmd, exit_code", [("true", 0), ("false", 1)]) diff --git a/tests/ert/unit_tests/services/test_base_service.py b/tests/ert/unit_tests/services/test_base_service.py index aced4fc6d23..39d801a6a38 100644 --- a/tests/ert/unit_tests/services/test_base_service.py +++ b/tests/ert/unit_tests/services/test_base_service.py @@ -241,9 +241,9 @@ def run(self): start_event.wait() # Client thread has started with _DummyService.start_server(exec_args=[str(server_script)]) as server: ready_event.wait() # Client thread has connected to server - assert not getattr( - client_thread, "exception", None - ), f"Exception from connect: {client_thread.exception}" + assert not getattr(client_thread, "exception", None), ( + f"Exception from connect: {client_thread.exception}" + ) client = client_thread.client assert client is not server assert client.fetch_conn_info() == server.fetch_conn_info() diff --git a/tests/ert/unit_tests/storage/test_local_storage.py b/tests/ert/unit_tests/storage/test_local_storage.py index 11645292656..2edf11cce8b 100644 --- a/tests/ert/unit_tests/storage/test_local_storage.py +++ b/tests/ert/unit_tests/storage/test_local_storage.py @@ -372,7 +372,7 @@ def test_that_open_storage_in_read_mode_with_newer_version_throws_exception( with pytest.raises( ErtStorageException, - match=f"Cannot open storage '{tmp_path}': Storage version {_LOCAL_STORAGE_VERSION+1} is newer than the current version {_LOCAL_STORAGE_VERSION}, upgrade ert to continue, or run with a different ENSPATH", + match=f"Cannot open storage '{tmp_path}': Storage version {_LOCAL_STORAGE_VERSION + 1} is newer than the current version {_LOCAL_STORAGE_VERSION}, upgrade ert to continue, or run with a different ENSPATH", ): open_storage(tmp_path, mode="r") @@ -386,7 +386,7 @@ def test_that_open_storage_in_read_mode_with_older_version_throws_exception( with pytest.raises( ErtStorageException, - match=f"Cannot open storage '{tmp_path}' in read-only mode: Storage version {_LOCAL_STORAGE_VERSION-1} is too old", + match=f"Cannot open storage '{tmp_path}' in read-only mode: Storage version {_LOCAL_STORAGE_VERSION - 1} is too old", ): open_storage(tmp_path, mode="r") @@ -400,7 +400,7 @@ def test_that_open_storage_in_write_mode_with_newer_version_throws_exception( with pytest.raises( ErtStorageException, - match=f"Cannot open storage '{tmp_path}': Storage version {_LOCAL_STORAGE_VERSION+1} is newer than the current version {_LOCAL_STORAGE_VERSION}, upgrade ert to continue, or run with a different ENSPATH", + match=f"Cannot open storage '{tmp_path}': Storage version {_LOCAL_STORAGE_VERSION + 1} is newer than the current version {_LOCAL_STORAGE_VERSION}, upgrade ert to continue, or run with a different ENSPATH", ): open_storage(tmp_path, mode="w") diff --git a/tests/ert/unit_tests/test_run_path_creation.py b/tests/ert/unit_tests/test_run_path_creation.py index 20423689328..37d35531fa4 100644 --- a/tests/ert/unit_tests/test_run_path_creation.py +++ b/tests/ert/unit_tests/test_run_path_creation.py @@ -509,7 +509,7 @@ def test_write_snakeoil_runpath_file(snake_oil_case, storage, itr): for run_arg in run_args: if not run_arg.active: continue - assert os.path.isdir(f"simulations/{10*run_arg.iens}") + assert os.path.isdir(f"simulations/{10 * run_arg.iens}") runpath_list_path = "a_file_name" assert os.path.isfile(runpath_list_path) diff --git a/tests/everest/test_logging.py b/tests/everest/test_logging.py index 9cc0b9b50dc..7b6e76addc7 100644 --- a/tests/everest/test_logging.py +++ b/tests/everest/test_logging.py @@ -70,7 +70,7 @@ async def server_running(): forward_model_log_path, "Exception: Failing simulation_2 by request!" ) assert _string_exists_in_file( - forward_model_log_path, "Exception: Failing simulation_2" " by request!" + forward_model_log_path, "Exception: Failing simulation_2 by request!" ) endpoint_logs = Path(endpoint_log_path).read_text(encoding="utf-8") diff --git a/tests/everest/test_templating.py b/tests/everest/test_templating.py index 6a551897003..f023752ce62 100644 --- a/tests/everest/test_templating.py +++ b/tests/everest/test_templating.py @@ -236,6 +236,6 @@ def test_user_specified_data_n_template( # Check expected contents of file with open(expected_file, encoding="utf-8") as f: contents = f.read() - assert ( - contents == "VALUE1+VALUE2" - ), f'Expected contents: "VALUE1+VALUE2", found: {contents}' + assert contents == "VALUE1+VALUE2", ( + f'Expected contents: "VALUE1+VALUE2", found: {contents}' + )