Skip to content

Commit d80c5d5

Browse files
committed
seleniumlib: config: Refactor functions
1 parent c6f671d commit d80c5d5

File tree

1 file changed

+24
-11
lines changed

1 file changed

+24
-11
lines changed

seleniumlib/config.py

Lines changed: 24 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
1+
import json
12
import os
23
import re
34
import sys
45
from pathlib import Path
56

6-
import json
77

8-
EXPR = re.compile(r"{{(.*?)}}")
8+
ENV_VAR_EXPR = re.compile(r"{{(.*?)}}")
99
os.environ["SCRIPT_DIR"] = str(Path(sys.argv[0]).parent)
1010

1111

1212
def extract_text_between_double_curly_braces(text):
13-
"""Extract text between double curly braces."""
13+
"""Extract environment variable between double curly braces."""
1414
try:
15-
return re.findall(EXPR, text)[0]
15+
return re.findall(ENV_VAR_EXPR, text)[0]
1616
except IndexError:
1717
return None
1818

@@ -23,24 +23,37 @@ def normalize_path(path, as_str=True):
2323
return str(n_path) if as_str else n_path
2424

2525

26-
def swap_env_vars(config):
27-
"""Swap environment variables with their values in config."""
26+
def expand_env_vars(config):
27+
"""Expand environment variables in config if they have been defined."""
2828
for section in config.keys():
2929
for key, value in config[section].items():
3030
if not isinstance(value, str):
3131
continue
32-
if env_var := extract_text_between_double_curly_braces(value):
32+
if env_var := extract_text_between_double_curly_braces(value) and os.environ.get(env_var):
3333
config[section][key] = value.replace("{{" + env_var + "}}", os.environ[env_var])
3434
if "path" in key:
3535
config[section][key] = normalize_path(config[section][key])
3636
return config
3737

3838

39+
def try_open_config_file(config_file):
40+
"""Try to open config file."""
41+
try:
42+
with open(config_file) as f:
43+
return json.load(f)
44+
except FileNotFoundError:
45+
print(f"Config file {config_file} not found.")
46+
sys.exit(1)
47+
48+
3949
def get_config():
40-
"""Return config after swapping environment variables."""
41-
with open("config.json") as f:
42-
config = json.load(f)
43-
return swap_env_vars(config)
50+
"""Return config after expanding environment variables.
51+
If SELENIUMLIB_CFG environment variable is defined, use that as config file."""
52+
if seleniumlib_cfg := os.environ.get("SELENIUMLIB_CFG"):
53+
config = try_open_config_file(seleniumlib_cfg)
54+
else:
55+
config = try_open_config_file("config.json")
56+
return expand_env_vars(config)
4457

4558

4659
def get_logging_options(config):

0 commit comments

Comments
 (0)