Skip to content

Commit

Permalink
Added saver to entrypoint, wrote tests
Browse files Browse the repository at this point in the history
  • Loading branch information
JoschD committed Jul 24, 2019
1 parent 01a7d1a commit 81244cb
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 8 deletions.
49 changes: 42 additions & 7 deletions omc3/generic_parser/entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ def _create_dict_parser(self):

def _create_config_parser(self):
""" Creates the config parser. Maybe more to do here later with parameter. """
parser = ConfigParser()
parser = ConfigParser({})
return parser

#########################
Expand Down Expand Up @@ -344,13 +344,18 @@ def _read_config(self, cfgfile_path, section=None):
cfgparse.read_file(config_file)

sections = cfgparse.sections()
if not section and len(sections) == 1:
section = sections[0]
elif not section:
raise ArgumentError(f"'{cfgfile_path:s}' contains multiple sections. " +
" Please specify one!")
if not section:
if len(sections) == 0:
section = "DEFAULT" # name does not matter, takes defaults, but None is not allowed
elif len(sections) == 1:
section = sections[0] # our convention
elif len(sections) > 1:
raise ArgumentError(f"'{cfgfile_path:s}' contains multiple sections. " +
" Please specify one!")

return cfgparse.items(section)
items = cfgparse.items(section)
self.configparse = self._create_config_parser() # clear the config parser, it keeps defaults between files
return items


# entrypoint Decorator #########################################################
Expand Down Expand Up @@ -649,3 +654,33 @@ def create_parameter_help(module, param_fun=None):
module._get_params().help()
else:
getattr(module, param_fun)().help()


def save_options_to_config(filepath, opt, unknown=None):
""" Saves the parsed options to a config file to be used as arguments.
Args:
filepath: path to write the config file to
opt: parsed known options
unknown: unknown options (only safe for non-commandline parameters)
"""
def _check_for_string(key, value):
if isinstance(value, str):
value = f'"{value}"'
return f"{key}={value}\n"

lines = "[DEFAULT]\n"
for o in opt:
lines += _check_for_string(o, opt[o])

if unknown is not None:
lines += "; Unknown options --------------------------\n"
if isinstance(unknown, dict):
for o in unknown:
lines += _check_for_string(o, unknown[o])
else:
lines += f"; {' '.join(unknown)}\n"

with open(filepath, "w") as f:
f.write(lines)
43 changes: 42 additions & 1 deletion tests/unit/test_entrypoint.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from generic_parser.entrypoint import (EntryPointParameters,
entrypoint, EntryPoint,
OptionsError, split_arguments,
create_parameter_help
create_parameter_help, save_options_to_config
)
from generic_parser.dict_parser import ParameterError, ArgumentError
from generic_parser.entry_datatypes import get_multi_class, DictAsString, BoolOrString, BoolOrList
Expand Down Expand Up @@ -194,6 +194,47 @@ def test_not_enough_length():
some_function(accel="LHCB1", anint=3, alist=[])


# Config Saver Test

def test_save_options():
opt, unknown = paramtest_function(
name="myname",
int=3,
list=[4, 5, 6],
unknown="myfinalargument",
unknoown=10,
)
with tempfile.TemporaryDirectory() as cwd:
cfg_file = os.path.join(cwd, "config.ini")
save_options_to_config(cfg_file, opt, unknown)
opt_load, unknown_load = paramtest_function(entry_cfg=cfg_file)

_assert_dicts(opt, opt_load)
_assert_dicts(unknown, unknown_load)


def test_save_cli_options():
opt, unknown = paramtest_function(
["--name", "myname",
"--int", "3",
"--list", "4", "5", "6",
"--other"]
)
with tempfile.TemporaryDirectory() as cwd:
cfg_file = os.path.join(cwd, "config.ini")
save_options_to_config(cfg_file, opt, unknown)
opt_load, unknown_load = paramtest_function(entry_cfg=cfg_file)

_assert_dicts(opt, opt_load)
assert len(unknown_load) == 0


def _assert_dicts(d1, d2):
for key in d1:
assert d1[key] == d2[key]
assert len(d2) == len(d1)


# Test Special Datatypes


Expand Down

0 comments on commit 81244cb

Please sign in to comment.