Skip to content

Commit a566bd2

Browse files
committed
test(config): add atomic unit tests for argparse ConfigResolver:
Add focused pytest unit tests covering load_config, str2bool, build_parser, resolve, logging level application, and input validation. All tests are isolated with mocked IO and fixtures, improving coverage and reliability.
1 parent e2acb83 commit a566bd2

7 files changed

Lines changed: 308 additions & 0 deletions

File tree

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from types import SimpleNamespace
2+
3+
import pytest
4+
5+
from CodeEntropy.config.argparse import ConfigResolver
6+
7+
8+
class DummyUniverse:
9+
"""Minimal MDAnalysis-like Universe stub for validate_inputs tests."""
10+
11+
def __init__(self, length: int):
12+
self.trajectory = [None] * length
13+
14+
15+
@pytest.fixture()
16+
def resolver():
17+
return ConfigResolver()
18+
19+
20+
@pytest.fixture()
21+
def dummy_universe():
22+
# default length used in many tests
23+
return DummyUniverse(length=100)
24+
25+
26+
@pytest.fixture()
27+
def make_args():
28+
"""Factory to build an args-like object with defaults used by validation checks."""
29+
30+
def _make(**overrides):
31+
base = dict(
32+
start=0,
33+
end=10,
34+
step=1,
35+
bin_width=30,
36+
temperature=298.0,
37+
force_partitioning=0.5,
38+
)
39+
base.update(overrides)
40+
# validation functions only require attribute access; SimpleNamespace is ideal
41+
return SimpleNamespace(**base)
42+
43+
return _make
44+
45+
46+
@pytest.fixture()
47+
def empty_cli_args(resolver):
48+
"""Argparse Namespace with all parser defaults."""
49+
parser = resolver.build_parser()
50+
return parser.parse_args([])
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
from CodeEntropy.config.argparse import ConfigResolver
2+
3+
4+
def test_build_parser_parses_selection_string():
5+
resolver = ConfigResolver()
6+
parser = resolver.build_parser()
7+
8+
args = parser.parse_args(["--selection_string", "protein"])
9+
10+
assert args.selection_string == "protein"
11+
12+
13+
def test_build_parser_parses_bool_with_str2bool():
14+
resolver = ConfigResolver()
15+
parser = resolver.build_parser()
16+
17+
args = parser.parse_args(["--kcal_force_units", "true"])
18+
19+
assert args.kcal_force_units is True
20+
21+
22+
def test_build_parser_store_true_flag_verbose_defaults_false_and_sets_true():
23+
resolver = ConfigResolver()
24+
parser = resolver.build_parser()
25+
26+
args_default = parser.parse_args([])
27+
assert args_default.verbose is False
28+
29+
args_verbose = parser.parse_args(["--verbose"])
30+
assert args_verbose.verbose is True
31+
32+
33+
def test_build_parser_nargs_plus_parses_top_traj_file_list():
34+
resolver = ConfigResolver()
35+
parser = resolver.build_parser()
36+
37+
args = parser.parse_args(["--top_traj_file", "a.tpr", "b.trr"])
38+
39+
assert args.top_traj_file == ["a.tpr", "b.trr"]
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from unittest.mock import mock_open, patch
2+
3+
from CodeEntropy.config.argparse import ConfigResolver
4+
5+
6+
def test_load_config_valid_yaml_returns_dict():
7+
yaml_content = """
8+
run1:
9+
selection_string: protein
10+
"""
11+
with (
12+
patch("glob.glob", return_value=["/fake/config.yaml"]),
13+
patch("builtins.open", mock_open(read_data=yaml_content)),
14+
):
15+
resolver = ConfigResolver()
16+
config = resolver.load_config("/fake")
17+
18+
assert "run1" in config
19+
assert config["run1"]["selection_string"] == "protein"
20+
21+
22+
def test_load_config_no_yaml_files_returns_default():
23+
with patch("glob.glob", return_value=[]):
24+
resolver = ConfigResolver()
25+
config = resolver.load_config("/fake")
26+
27+
assert config == {"run1": {}}
28+
29+
30+
def test_load_config_yaml_empty_returns_default_run1():
31+
yaml_content = "" # yaml.safe_load -> None
32+
with (
33+
patch("glob.glob", return_value=["/fake/config.yaml"]),
34+
patch("builtins.open", mock_open(read_data=yaml_content)),
35+
):
36+
resolver = ConfigResolver()
37+
config = resolver.load_config("/fake")
38+
39+
assert config == {"run1": {}}
40+
41+
42+
def test_load_config_open_error_returns_default():
43+
with (
44+
patch("glob.glob", return_value=["/fake/config.yaml"]),
45+
patch("builtins.open", side_effect=OSError("boom")),
46+
):
47+
resolver = ConfigResolver()
48+
config = resolver.load_config("/fake")
49+
50+
assert config == {"run1": {}}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import logging
2+
3+
import pytest
4+
5+
from CodeEntropy.config.argparse import ConfigResolver, logger
6+
7+
8+
def test_resolve_run_config_wrong_type_raises_type_error(resolver, empty_cli_args):
9+
with pytest.raises(TypeError):
10+
resolver.resolve(empty_cli_args, run_config="not-a-dict")
11+
12+
13+
def test_resolve_none_run_config_treated_as_empty(resolver, empty_cli_args):
14+
resolved = resolver.resolve(empty_cli_args, None)
15+
# should still have defaults applied
16+
assert resolved.selection_string is not None
17+
18+
19+
def test_resolve_yaml_applied_when_cli_not_provided(resolver, empty_cli_args):
20+
run_config = {"selection_string": "yaml_value"}
21+
22+
resolved = resolver.resolve(empty_cli_args, run_config)
23+
24+
assert resolved.selection_string == "yaml_value"
25+
26+
27+
def test_resolve_cli_value_overrides_yaml(resolver):
28+
parser = resolver.build_parser()
29+
args = parser.parse_args(["--selection_string", "cli_value"])
30+
run_config = {"selection_string": "yaml_value"}
31+
32+
resolved = resolver.resolve(args, run_config)
33+
34+
assert resolved.selection_string == "cli_value"
35+
36+
37+
def test_resolve_does_not_apply_yaml_key_not_in_arg_specs(resolver, empty_cli_args):
38+
run_config = {"not_a_real_arg": 123}
39+
40+
resolved = resolver.resolve(empty_cli_args, run_config)
41+
42+
assert not hasattr(resolved, "not_a_real_arg")
43+
44+
45+
def test_resolve_ensure_defaults_sets_none_values(resolver):
46+
# If a known arg is None, _ensure_defaults should fill it.
47+
parser = resolver.build_parser()
48+
args = parser.parse_args([])
49+
50+
# force a known arg to None to simulate partial/mutated namespace
51+
args.selection_string = None
52+
53+
resolved = resolver.resolve(args, {})
54+
55+
assert resolved.selection_string == "all"
56+
57+
58+
def test_resolve_verbose_sets_logger_debug_level(resolver):
59+
parser = resolver.build_parser()
60+
args = parser.parse_args(["--verbose"])
61+
62+
resolver.resolve(args, {})
63+
64+
assert logger.level == logging.DEBUG
65+
66+
67+
def test_apply_logging_level_updates_handler_level():
68+
handler = logging.StreamHandler()
69+
handler.setLevel(logging.WARNING)
70+
logger.addHandler(handler)
71+
72+
try:
73+
ConfigResolver._apply_logging_level(verbose=True)
74+
assert logger.level == logging.DEBUG
75+
assert handler.level == logging.DEBUG
76+
finally:
77+
logger.removeHandler(handler)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import argparse as _argparse
2+
3+
import pytest
4+
5+
from CodeEntropy.config.argparse import ConfigResolver
6+
7+
8+
@pytest.mark.parametrize("value", ["true", "True", "t", "yes", "1"])
9+
def test_str2bool_true_variants(value):
10+
assert ConfigResolver.str2bool(value) is True
11+
12+
13+
@pytest.mark.parametrize("value", ["false", "False", "f", "no", "0"])
14+
def test_str2bool_false_variants(value):
15+
assert ConfigResolver.str2bool(value) is False
16+
17+
18+
def test_str2bool_bool_passthrough():
19+
assert ConfigResolver.str2bool(True) is True
20+
assert ConfigResolver.str2bool(False) is False
21+
22+
23+
def test_str2bool_non_string_non_bool_raises():
24+
with pytest.raises(_argparse.ArgumentTypeError):
25+
ConfigResolver.str2bool(123)
26+
27+
28+
def test_str2bool_invalid_string_raises():
29+
with pytest.raises(_argparse.ArgumentTypeError):
30+
ConfigResolver.str2bool("maybe")
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import logging
2+
3+
import pytest
4+
5+
6+
def test_validate_inputs_valid_does_not_raise(resolver, dummy_universe, make_args):
7+
args = make_args()
8+
resolver.validate_inputs(dummy_universe, args)
9+
10+
11+
def test_check_input_start_raises_when_start_exceeds_trajectory(resolver, make_args):
12+
u = type("U", (), {"trajectory": [None] * 10})()
13+
args = make_args(start=11)
14+
15+
with pytest.raises(ValueError):
16+
resolver._check_input_start(u, args)
17+
18+
19+
def test_check_input_end_raises_when_end_exceeds_trajectory(resolver, make_args):
20+
u = type("U", (), {"trajectory": [None] * 10})()
21+
args = make_args(end=11)
22+
23+
with pytest.raises(ValueError):
24+
resolver._check_input_end(u, args)
25+
26+
27+
def test_check_input_step_negative_logs_warning(resolver, make_args, caplog):
28+
args = make_args(step=-1)
29+
30+
with caplog.at_level(logging.WARNING):
31+
resolver._check_input_step(args)
32+
33+
assert "Negative 'step' value" in caplog.text
34+
35+
36+
@pytest.mark.parametrize("bin_width", [-1, 361])
37+
def test_check_input_bin_width_out_of_range_raises(resolver, make_args, bin_width):
38+
args = make_args(bin_width=bin_width)
39+
40+
with pytest.raises(ValueError):
41+
resolver._check_input_bin_width(args)
42+
43+
44+
def test_check_input_temperature_negative_raises(resolver, make_args):
45+
args = make_args(temperature=-0.1)
46+
47+
with pytest.raises(ValueError):
48+
resolver._check_input_temperature(args)
49+
50+
51+
def test_check_input_force_partitioning_non_default_logs_warning(
52+
resolver, make_args, caplog
53+
):
54+
args = make_args(force_partitioning=0.7)
55+
56+
with caplog.at_level(logging.WARNING):
57+
resolver._check_input_force_partitioning(args)
58+
59+
assert "differs from the default" in caplog.text

‎tests/unit/CodeEntropy/pytest.ini‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
[pytest]
2+
testpaths = CodeEntropy/tests/unit
3+
addopts = -q

0 commit comments

Comments
 (0)