From af7a52637018392f300ddbbb535f270b595cda25 Mon Sep 17 00:00:00 2001 From: PranjalManhgaye Date: Fri, 21 Aug 2026 02:47:57 +0530 Subject: [PATCH 1/2] Fix per-component build arguments in system tests. Each Docker service now gets its own build arguments from components.yaml instead of sharing one merged dict that could overwrite PLATFORM and PRECICE_REF across participants. Fixes #873 --- changelog-entries/907.md | 1 + tests/systemtests/Systemtest.py | 159 +++++++++++++++---------- tests/test_per_component_build_args.py | 123 +++++++++++++++++++ 3 files changed, 222 insertions(+), 61 deletions(-) create mode 100644 changelog-entries/907.md create mode 100644 tests/test_per_component_build_args.py diff --git a/changelog-entries/907.md b/changelog-entries/907.md new file mode 100644 index 000000000..0f69f24d0 --- /dev/null +++ b/changelog-entries/907.md @@ -0,0 +1 @@ +- Fixed `Systemtest.py` so each Docker service receives its own build arguments from `components.yaml` (e.g. per-component `PLATFORM` and `PRECICE_REF`) instead of sharing one merged dict that could overwrite values across participants. [#907](https://github.com/precice/tutorials/pull/907) diff --git a/tests/systemtests/Systemtest.py b/tests/systemtests/Systemtest.py index 5e497d9bc..d5f32422e 100644 --- a/tests/systemtests/Systemtest.py +++ b/tests/systemtests/Systemtest.py @@ -239,6 +239,7 @@ class Systemtest: run_before: str | None = None run_after: str | None = None params_to_use: Dict[str, str] = field(init=False) + build_arguments_by_component: Dict[str, Dict[str, str]] = field(init=False) env: Dict[str, str] = field(init=False) def __eq__(self, other) -> bool: @@ -279,38 +280,75 @@ def _resolve_build_timeout(self) -> int: def __init_args_to_use(self): """ - Forwards the command-line arguments to the params_to_use dictionary, substituting any missing arguments with their defaults. - - Previously, this function was also checking if all required parameters were provided, and was raising exceptions for parameters not provided and not having a default value. This check made adding optional parameters with empty defaults (e.g., the TUTORIALS_PR) complicated, and it was removed. + Resolve build arguments per component from components.yaml defaults and + global CLI overrides, then merge them for shared stages (prepare). """ - - # Forward all provided arguments to params_to_use provided_arguments = self.arguments.arguments - self.params_to_use = provided_arguments + self.build_arguments_by_component = {} - # Find out which parameters are needed - needed_parameters = set() for case in self.case_combination.cases: - needed_parameters.update(case.component.parameters) - - # Substitute defaults for non-provided, needed arguments - for needed_param in needed_parameters: - if not needed_param.key in provided_arguments: - logging.info( - f"No argument provided for needed parameter {needed_param.key}. Substituting with {needed_param.default}.") - self.params_to_use[needed_param.key] = needed_param.default - if needed_param.key.endswith("_REF") and needed_param.key in provided_arguments: - logging.debug( - f"The parameter {needed_param.key} points to the repository {needed_param.repository}.") - # If a commit has already been resolved and added to the params_to_use, it will be propagated to the next test in the test suite. - # To avoid resolving the same commit again, simply check if the key has the same length as the output of _resolve_branch_ref_to_commit. - # The whole process assumes that all components use the same refs. - if len(self.params_to_use[needed_param.key]) == 40: - logging.debug( - f"Git ref {self.params_to_use[needed_param.key]} is 40 characters long and probably already a commit.") + component = case.component + if component.name in self.build_arguments_by_component: + continue + + component_args: Dict[str, str] = {} + for param in component.parameters: + if param.key not in provided_arguments: + logging.info( + f"No argument provided for needed parameter {param.key} " + f"on component {component.name}. " + f"Substituting with {param.default}.") + value = param.default else: - self.params_to_use[needed_param.key] = self._resolve_branch_ref_to_commit( - needed_param.repository, self.params_to_use[needed_param.key]) + value = provided_arguments[param.key] + + if param.key.endswith("_REF") and param.key in provided_arguments: + logging.debug( + f"The parameter {param.key} on component {component.name} " + f"points to the repository {param.repository}.") + if value and len(value) != 40: + value = self._resolve_branch_ref_to_commit( + param.repository, value) + provided_arguments[param.key] = value + + component_args[param.key] = value + + self.build_arguments_by_component[component.name] = component_args + + self.params_to_use = self._merged_build_arguments() + + def _primary_case(self) -> Case: + return self.case_combination.cases[0] + + def _primary_platform(self) -> str | None: + return self.build_arguments_by_component[ + self._primary_case().component.name + ].get("PLATFORM") + + def _dockerfile_context_relative(self, platform: str) -> Path: + return Path("..") / "tests" / "dockerfiles" / Path(platform) + + def _merged_build_arguments(self) -> Dict[str, str]: + merged: Dict[str, str] = {} + for case in self.case_combination.cases: + component_args = self.build_arguments_by_component[case.component.name] + for key, value in component_args.items(): + if key in merged and merged[key] != value: + logging.warning( + f"Build argument '{key}' differs between components " + f"({merged[key]!r} vs {value!r}); using {merged[key]!r} " + f"for shared build stages.") + elif key not in merged: + merged[key] = value + return merged + + def _validate_dockerfile_platform(self, platform: str, context: str = "") -> None: + dockerfile_context = PRECICE_TESTS_DIR / "dockerfiles" / Path(platform) + if not dockerfile_context.exists(): + suffix = f" for {context}" if context else "" + raise ValueError( + f"The path {dockerfile_context.resolve()} resulting from argument " + f"PLATFORM={platform}{suffix} could not be found in the system") def __get_docker_services(self) -> Dict[str, str]: """ @@ -319,39 +357,38 @@ def __get_docker_services(self) -> Dict[str, str]: Returns: A dictionary of rendered services per case name. """ - platform_requested = self.params_to_use.get("PLATFORM") + seen_platforms: set[str] = set() + for case in self.case_combination.cases: + platform = self.build_arguments_by_component[case.component.name].get( + "PLATFORM") + if platform and platform not in seen_platforms: + self._validate_dockerfile_platform( + platform, f"component {case.component.name}") + seen_platforms.add(platform) + + primary_platform = self._primary_platform() + if not primary_platform: + raise KeyError("Please specify a PLATFORM argument") + self.dockerfile_context = ( + PRECICE_TESTS_DIR / "dockerfiles" / Path(primary_platform) + ) - # Use an absolute path here only for validation that the requested - # dockerfile context exists on the machine running the system tests. - self.dockerfile_context = PRECICE_TESTS_DIR / "dockerfiles" / Path(platform_requested) - if not self.dockerfile_context.exists(): - raise ValueError( - f"The path {self.dockerfile_context.resolve()} resulting from argument PLATFORM={platform_requested} could not be found in the system") - - def render_service_template_per_case(case: Case, params_to_use: Dict[str, str]) -> str: - # Inside the individual system test directory (`self.system_test_dir`) - # we copy a full `tests/` tree into the parent run directory - # (see __copy_tools_and_tests). From the point of view of the system test - # directory we therefore need to go one level up to reach the - # shared `tests/` folder: - # /tests/dockerfiles/ - # ^-------------^ parent of self.system_test_dir - dockerfile_context_relative = ( - Path("..") / "tests" / "dockerfiles" / Path(platform_requested) - ) + def render_service_template_per_case(case: Case) -> str: + build_arguments = self.build_arguments_by_component[case.component.name] + platform = build_arguments.get("PLATFORM") + if not platform: + raise KeyError( + f"Please specify a PLATFORM argument for component " + f"{case.component.name}") render_dict = { - # Use a relative path to the *parent* run directory so that - # containers still see /runs/ like before, - # while keeping the compose file independent of the CI - # runner's absolute paths. 'run_directory': "..", 'tutorial_folder': self.tutorial_folder, - 'build_arguments': params_to_use, - 'params': params_to_use, + 'build_arguments': build_arguments, + 'params': build_arguments, 'case_folder': case.path, 'run': case.run_cmd, - 'dockerfile_context': dockerfile_context_relative, + 'dockerfile_context': self._dockerfile_context_relative(platform), } jinja_env = Environment(loader=FileSystemLoader(PRECICE_TESTS_DIR)) template = jinja_env.get_template(case.component.template) @@ -359,8 +396,7 @@ def render_service_template_per_case(case: Case, params_to_use: Dict[str, str]) rendered_services = {} for case in self.case_combination.cases: - rendered_services[case.name] = render_service_template_per_case( - case, self.params_to_use) + rendered_services[case.name] = render_service_template_per_case(case) return rendered_services def __get_docker_compose_file(self): @@ -377,9 +413,8 @@ def __get_docker_compose_file(self): # used as a build context path and does not need to be # absolute – it will be resolved relative to the system test # directory. - 'dockerfile_context': ( - Path("..") / "tests" / "dockerfiles" / Path(self.params_to_use.get("PLATFORM")) - ), + 'dockerfile_context': self._dockerfile_context_relative( + self._primary_platform()), 'precice_output_folder': PRECICE_REL_OUTPUT_DIR, } jinja_env = Environment(loader=FileSystemLoader(PRECICE_TESTS_DIR)) @@ -400,9 +435,8 @@ def __get_field_compare_compose_file(self): # used as a build context path and does not need to be # absolute – it will be resolved relative to the system test # directory. - 'dockerfile_context': ( - Path("..") / "tests" / "dockerfiles" / Path(self.params_to_use.get("PLATFORM")) - ), + 'dockerfile_context': self._dockerfile_context_relative( + self._primary_platform()), } jinja_env = Environment(loader=FileSystemLoader(PRECICE_TESTS_DIR)) template = jinja_env.get_template( @@ -1075,6 +1109,9 @@ def __prepare_for_run(self, run_directory: Path): host_uid, host_gid = self.__get_uid_gid() self.params_to_use['PRECICE_UID'] = host_uid self.params_to_use['PRECICE_GID'] = host_gid + for component_args in self.build_arguments_by_component.values(): + component_args['PRECICE_UID'] = host_uid + component_args['PRECICE_GID'] = host_gid def run(self, run_directory: Path): """ diff --git a/tests/test_per_component_build_args.py b/tests/test_per_component_build_args.py new file mode 100644 index 000000000..07b327953 --- /dev/null +++ b/tests/test_per_component_build_args.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Unit tests for per-component build arguments (issue #873).""" + +from __future__ import annotations + +import logging +import os +import unittest +from pathlib import Path + +from metadata_parser.metdata import ( + CaseCombination, + Components, + ReferenceResult, + Tutorial, +) +from paths import PRECICE_TESTS_DIR, PRECICE_TUTORIAL_DIR +from systemtests.Systemtest import Systemtest +from systemtests.SystemtestArguments import SystemtestArguments + +logging.disable(logging.CRITICAL) + + +def _patch_param_default(case_combination, component_name: str, key: str, value: str) -> None: + for case in case_combination.cases: + if case.component.name != component_name: + continue + for param in case.component.parameters: + if param.key == key: + param.default = value + + +def _load_quickstart_systemtest( + build_args: SystemtestArguments | None = None, + patches: list[tuple[str, str, str]] | None = None, +) -> tuple[Systemtest, CaseCombination]: + components = Components.from_yaml(PRECICE_TESTS_DIR / "components.yaml") + tutorial = Tutorial.from_yaml( + PRECICE_TUTORIAL_DIR / "quickstart" / "metadata.yaml", + components, + ) + case_combination = CaseCombination.from_string_list( + ["fluid-openfoam", "solid-cpp"], tutorial) + reference_result = ReferenceResult( + Path("quickstart/reference-results/fluid-openfoam_solid-cpp.tar.gz"), + case_combination, + ) + + if patches: + for component_name, key, value in patches: + _patch_param_default(case_combination, component_name, key, value) + + systemtest = Systemtest( + tutorial, + build_args or SystemtestArguments({}), + case_combination, + reference_result, + ) + systemtest.run_directory = PRECICE_TESTS_DIR.parent / "runs" / "issue873-test" + systemtest.tutorial_folder = "quickstart_issue873_test" + return systemtest, case_combination + + +class PerComponentBuildArgsTest(unittest.TestCase): + @classmethod + def setUpClass(cls) -> None: + alt_platform = PRECICE_TESTS_DIR / "dockerfiles" / "ubuntu_2404_bare" + target = PRECICE_TESTS_DIR / "dockerfiles" / "ubuntu_2404" + if not alt_platform.exists(): + alt_platform.symlink_to(target, target_is_directory=True) + + def test_same_defaults_regression(self) -> None: + systemtest, _ = _load_quickstart_systemtest() + bare = systemtest.build_arguments_by_component["bare"] + openfoam = systemtest.build_arguments_by_component["openfoam-adapter"] + self.assertEqual(bare.get("PLATFORM"), "ubuntu_2404") + self.assertEqual(openfoam.get("PLATFORM"), "ubuntu_2404") + self.assertIsNot(systemtest.params_to_use, systemtest.arguments.arguments) + + def test_different_platform_per_component(self) -> None: + systemtest, _ = _load_quickstart_systemtest( + patches=[("bare", "PLATFORM", "ubuntu_2404_bare")]) + + bare = systemtest.build_arguments_by_component["bare"] + openfoam = systemtest.build_arguments_by_component["openfoam-adapter"] + self.assertEqual(bare.get("PLATFORM"), "ubuntu_2404_bare") + self.assertEqual(openfoam.get("PLATFORM"), "ubuntu_2404") + + compose = systemtest._Systemtest__get_docker_compose_file() + self.assertIn("ubuntu_2404_bare", compose) + self.assertIn("ubuntu_2404", compose.replace("ubuntu_2404_bare", "")) + + def test_different_precice_ref_per_component(self) -> None: + systemtest, _ = _load_quickstart_systemtest( + patches=[ + ("bare", "PRECICE_REF", "bare-ref"), + ("openfoam-adapter", "PRECICE_REF", "openfoam-ref"), + ]) + + bare = systemtest.build_arguments_by_component["bare"] + openfoam = systemtest.build_arguments_by_component["openfoam-adapter"] + self.assertEqual(bare.get("PRECICE_REF"), "bare-ref") + self.assertEqual(openfoam.get("PRECICE_REF"), "openfoam-ref") + + compose = systemtest._Systemtest__get_docker_compose_file() + self.assertIn("PRECICE_REF=bare-ref", compose) + self.assertIn("PRECICE_REF=openfoam-ref", compose) + + def test_global_cli_override(self) -> None: + systemtest, _ = _load_quickstart_systemtest( + SystemtestArguments({"PLATFORM": "ubuntu_2404"}), + patches=[("bare", "PLATFORM", "ubuntu_2404_bare")], + ) + + for component_name in ("bare", "openfoam-adapter"): + platform = systemtest.build_arguments_by_component[component_name].get( + "PLATFORM") + self.assertEqual(platform, "ubuntu_2404") + + +if __name__ == "__main__": + os.chdir(PRECICE_TESTS_DIR) + unittest.main() From b23a4afe26ce8c7e53eade41029cba8f8a49b2fb Mon Sep 17 00:00:00 2001 From: PranjalManhgaye Date: Mon, 24 Aug 2026 23:08:35 +0530 Subject: [PATCH 2/2] Address review: remove unit tests, restore comments, shorten changelog. --- changelog-entries/907.md | 2 +- tests/systemtests/Systemtest.py | 29 +++++- tests/test_per_component_build_args.py | 123 ------------------------- 3 files changed, 28 insertions(+), 126 deletions(-) delete mode 100644 tests/test_per_component_build_args.py diff --git a/changelog-entries/907.md b/changelog-entries/907.md index 0f69f24d0..8d9f5ea65 100644 --- a/changelog-entries/907.md +++ b/changelog-entries/907.md @@ -1 +1 @@ -- Fixed `Systemtest.py` so each Docker service receives its own build arguments from `components.yaml` (e.g. per-component `PLATFORM` and `PRECICE_REF`) instead of sharing one merged dict that could overwrite values across participants. [#907](https://github.com/precice/tutorials/pull/907) +- Fixed `Systemtest.py` so each Docker service receives its own build arguments from `components.yaml` (e.g. per-component `PLATFORM` and `PRECICE_REF`). [#907](https://github.com/precice/tutorials/pull/907) diff --git a/tests/systemtests/Systemtest.py b/tests/systemtests/Systemtest.py index d5f32422e..01bf71f0d 100644 --- a/tests/systemtests/Systemtest.py +++ b/tests/systemtests/Systemtest.py @@ -282,6 +282,8 @@ def __init_args_to_use(self): """ Resolve build arguments per component from components.yaml defaults and global CLI overrides, then merge them for shared stages (prepare). + + Previously, this function was also checking if all required parameters were provided, and was raising exceptions for parameters not provided and not having a default value. This check made adding optional parameters with empty defaults (e.g., the TUTORIALS_PR) complicated, and it was removed. """ provided_arguments = self.arguments.arguments self.build_arguments_by_component = {} @@ -306,7 +308,15 @@ def __init_args_to_use(self): logging.debug( f"The parameter {param.key} on component {component.name} " f"points to the repository {param.repository}.") - if value and len(value) != 40: + # If a commit has already been resolved and added to the build + # arguments, it will be propagated to the next test in the test suite. + # To avoid resolving the same commit again, simply check if the key + # has the same length as the output of _resolve_branch_ref_to_commit. + # The whole process assumes that all components use the same refs. + if value and len(value) == 40: + logging.debug( + f"Git ref {value} is 40 characters long and probably already a commit.") + elif value and len(value) != 40: value = self._resolve_branch_ref_to_commit( param.repository, value) provided_arguments[param.key] = value @@ -343,6 +353,8 @@ def _merged_build_arguments(self) -> Dict[str, str]: return merged def _validate_dockerfile_platform(self, platform: str, context: str = "") -> None: + # Use an absolute path here only for validation that the requested + # dockerfile context exists on the machine running the system tests. dockerfile_context = PRECICE_TESTS_DIR / "dockerfiles" / Path(platform) if not dockerfile_context.exists(): suffix = f" for {context}" if context else "" @@ -381,14 +393,27 @@ def render_service_template_per_case(case: Case) -> str: f"Please specify a PLATFORM argument for component " f"{case.component.name}") + # Inside the individual system test directory (`self.system_test_dir`) + # we copy a full `tests/` tree into the parent run directory + # (see __copy_tools_and_tests). From the point of view of the system test + # directory we therefore need to go one level up to reach the + # shared `tests/` folder: + # /tests/dockerfiles/ + # ^-------------^ parent of self.system_test_dir + dockerfile_context_relative = self._dockerfile_context_relative(platform) + render_dict = { + # Use a relative path to the *parent* run directory so that + # containers still see /runs/ like before, + # while keeping the compose file independent of the CI + # runner's absolute paths. 'run_directory': "..", 'tutorial_folder': self.tutorial_folder, 'build_arguments': build_arguments, 'params': build_arguments, 'case_folder': case.path, 'run': case.run_cmd, - 'dockerfile_context': self._dockerfile_context_relative(platform), + 'dockerfile_context': dockerfile_context_relative, } jinja_env = Environment(loader=FileSystemLoader(PRECICE_TESTS_DIR)) template = jinja_env.get_template(case.component.template) diff --git a/tests/test_per_component_build_args.py b/tests/test_per_component_build_args.py deleted file mode 100644 index 07b327953..000000000 --- a/tests/test_per_component_build_args.py +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env python3 -"""Unit tests for per-component build arguments (issue #873).""" - -from __future__ import annotations - -import logging -import os -import unittest -from pathlib import Path - -from metadata_parser.metdata import ( - CaseCombination, - Components, - ReferenceResult, - Tutorial, -) -from paths import PRECICE_TESTS_DIR, PRECICE_TUTORIAL_DIR -from systemtests.Systemtest import Systemtest -from systemtests.SystemtestArguments import SystemtestArguments - -logging.disable(logging.CRITICAL) - - -def _patch_param_default(case_combination, component_name: str, key: str, value: str) -> None: - for case in case_combination.cases: - if case.component.name != component_name: - continue - for param in case.component.parameters: - if param.key == key: - param.default = value - - -def _load_quickstart_systemtest( - build_args: SystemtestArguments | None = None, - patches: list[tuple[str, str, str]] | None = None, -) -> tuple[Systemtest, CaseCombination]: - components = Components.from_yaml(PRECICE_TESTS_DIR / "components.yaml") - tutorial = Tutorial.from_yaml( - PRECICE_TUTORIAL_DIR / "quickstart" / "metadata.yaml", - components, - ) - case_combination = CaseCombination.from_string_list( - ["fluid-openfoam", "solid-cpp"], tutorial) - reference_result = ReferenceResult( - Path("quickstart/reference-results/fluid-openfoam_solid-cpp.tar.gz"), - case_combination, - ) - - if patches: - for component_name, key, value in patches: - _patch_param_default(case_combination, component_name, key, value) - - systemtest = Systemtest( - tutorial, - build_args or SystemtestArguments({}), - case_combination, - reference_result, - ) - systemtest.run_directory = PRECICE_TESTS_DIR.parent / "runs" / "issue873-test" - systemtest.tutorial_folder = "quickstart_issue873_test" - return systemtest, case_combination - - -class PerComponentBuildArgsTest(unittest.TestCase): - @classmethod - def setUpClass(cls) -> None: - alt_platform = PRECICE_TESTS_DIR / "dockerfiles" / "ubuntu_2404_bare" - target = PRECICE_TESTS_DIR / "dockerfiles" / "ubuntu_2404" - if not alt_platform.exists(): - alt_platform.symlink_to(target, target_is_directory=True) - - def test_same_defaults_regression(self) -> None: - systemtest, _ = _load_quickstart_systemtest() - bare = systemtest.build_arguments_by_component["bare"] - openfoam = systemtest.build_arguments_by_component["openfoam-adapter"] - self.assertEqual(bare.get("PLATFORM"), "ubuntu_2404") - self.assertEqual(openfoam.get("PLATFORM"), "ubuntu_2404") - self.assertIsNot(systemtest.params_to_use, systemtest.arguments.arguments) - - def test_different_platform_per_component(self) -> None: - systemtest, _ = _load_quickstart_systemtest( - patches=[("bare", "PLATFORM", "ubuntu_2404_bare")]) - - bare = systemtest.build_arguments_by_component["bare"] - openfoam = systemtest.build_arguments_by_component["openfoam-adapter"] - self.assertEqual(bare.get("PLATFORM"), "ubuntu_2404_bare") - self.assertEqual(openfoam.get("PLATFORM"), "ubuntu_2404") - - compose = systemtest._Systemtest__get_docker_compose_file() - self.assertIn("ubuntu_2404_bare", compose) - self.assertIn("ubuntu_2404", compose.replace("ubuntu_2404_bare", "")) - - def test_different_precice_ref_per_component(self) -> None: - systemtest, _ = _load_quickstart_systemtest( - patches=[ - ("bare", "PRECICE_REF", "bare-ref"), - ("openfoam-adapter", "PRECICE_REF", "openfoam-ref"), - ]) - - bare = systemtest.build_arguments_by_component["bare"] - openfoam = systemtest.build_arguments_by_component["openfoam-adapter"] - self.assertEqual(bare.get("PRECICE_REF"), "bare-ref") - self.assertEqual(openfoam.get("PRECICE_REF"), "openfoam-ref") - - compose = systemtest._Systemtest__get_docker_compose_file() - self.assertIn("PRECICE_REF=bare-ref", compose) - self.assertIn("PRECICE_REF=openfoam-ref", compose) - - def test_global_cli_override(self) -> None: - systemtest, _ = _load_quickstart_systemtest( - SystemtestArguments({"PLATFORM": "ubuntu_2404"}), - patches=[("bare", "PLATFORM", "ubuntu_2404_bare")], - ) - - for component_name in ("bare", "openfoam-adapter"): - platform = systemtest.build_arguments_by_component[component_name].get( - "PLATFORM") - self.assertEqual(platform, "ubuntu_2404") - - -if __name__ == "__main__": - os.chdir(PRECICE_TESTS_DIR) - unittest.main()