diff --git a/lib/galaxy/util/properties.py b/lib/galaxy/util/properties.py index df33637a117..64318c6d5c0 100644 --- a/lib/galaxy/util/properties.py +++ b/lib/galaxy/util/properties.py @@ -31,6 +31,22 @@ from galaxy.util.path import ( ) +def get_from_env(key: str, prefixes: Iterable[str], default: Optional[str] = None): + """ + Return first available value for prefix+key set in the environment, or default. + An empty prefix is ignored. + + Useful when we need to check against multiple prefixes sequentially, + returning the first available value. + """ + for prefix in prefixes: + if prefix: + value = os.getenv(f"{prefix}{key}") + if value: + return value + return default + + def find_config_file(names, exts=None, dirs=None, include_samples=False): """Locate a config file in multiple directories, with multiple extensions. diff --git a/test/unit/util/test_properties.py b/test/unit/util/test_properties.py index 9c0a9bdcc13..4817c83e1c9 100644 --- a/test/unit/util/test_properties.py +++ b/test/unit/util/test_properties.py @@ -1,8 +1,11 @@ +import os + import pytest from galaxy.exceptions import InvalidFileFormatError from galaxy.util import properties from galaxy.util.properties import ( + get_from_env, nice_config_parser, read_properties_from_file, ) @@ -12,6 +15,28 @@ VAL1, VAL2, VAL3, VAL4, VAL5, VAL6 = 1, 2, 3, 4, 5, 6 OTHER_SECTION = "other" +def test_get_from_env(monkeypatch): + prefixes = ["pre1_", "pre2_", "pre3_"] + + monkeypatch.setenv("pre1_a", "a-is-set") + monkeypatch.setenv("pre2_b", "b-is-set") + + assert get_from_env("a", prefixes, "a-default") == "a-is-set" # selected from first prefix + assert get_from_env("b", prefixes, "b-default") == "b-is-set" # selected from second prefix + assert get_from_env("c", prefixes, "c-default") == "c-default" # default + + +def test_get_from_env__no_default(monkeypatch): + assert get_from_env("a", ["some", "random", "prefixes"]) is None + + +def test_get_from_env__empty_prefix_ignored(monkeypatch): + monkeypatch.setenv("a", "a-without-prefix-is-set") + assert os.getenv("a") == "a-without-prefix-is-set" + + assert get_from_env("a", ["", None], "a-default") == "a-default" + + @pytest.fixture def mock_properties(monkeypatch): # Keys in defaults dict and other dicts should not intersect. The tests assume