Skip to content

Commit 11ecb86

Browse files
committed
test(config): refactor runtime tests into atomic unit suite with mocks and branch coverage
1 parent c03aad8 commit 11ecb86

11 files changed

Lines changed: 370 additions & 0 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import pytest
2+
3+
from CodeEntropy.config.runtime import CodeEntropyRunner
4+
5+
6+
@pytest.fixture()
7+
def runner(tmp_path, monkeypatch):
8+
# keep filesystem effects isolated
9+
monkeypatch.chdir(tmp_path)
10+
return CodeEntropyRunner(folder=str(tmp_path))
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from types import SimpleNamespace
2+
from unittest.mock import MagicMock, patch
3+
4+
5+
def test_build_universe_no_force(runner):
6+
args = SimpleNamespace(
7+
top_traj_file=["tpr", "trr"],
8+
force_file=None,
9+
file_format=None,
10+
kcal_force_units=False,
11+
)
12+
uops = MagicMock()
13+
14+
with patch("CodeEntropy.config.runtime.mda.Universe", return_value="U"):
15+
out = runner._build_universe(args, uops)
16+
17+
assert out == "U"
18+
uops.merge_forces.assert_not_called()
19+
20+
21+
def test_build_universe_with_force(runner):
22+
args = SimpleNamespace(
23+
top_traj_file=["tpr", "trr"],
24+
force_file="force",
25+
file_format="gro",
26+
kcal_force_units=True,
27+
)
28+
uops = MagicMock()
29+
uops.merge_forces.return_value = "U2"
30+
31+
out = runner._build_universe(args, uops)
32+
33+
assert out == "U2"
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from unittest.mock import MagicMock, patch
2+
3+
import requests
4+
5+
6+
def test_load_citation_data_success(runner):
7+
mock_response = MagicMock()
8+
mock_response.raise_for_status.return_value = None
9+
mock_response.text = """
10+
title: TestProject
11+
authors:
12+
- given-names: Alice
13+
"""
14+
15+
with patch("requests.get", return_value=mock_response):
16+
data = runner.load_citation_data()
17+
18+
assert data["title"] == "TestProject"
19+
20+
21+
def test_load_citation_data_network_error_returns_none(runner):
22+
with patch("requests.get", side_effect=requests.exceptions.ConnectionError()):
23+
assert runner.load_citation_data() is None
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import os
2+
from unittest.mock import patch
3+
4+
from CodeEntropy.config.runtime import CodeEntropyRunner
5+
6+
7+
def test_create_job_folder_empty_creates_job001():
8+
with (
9+
patch("os.getcwd", return_value="/cwd"),
10+
patch("os.listdir", return_value=[]),
11+
patch("os.makedirs") as mock_makedirs,
12+
):
13+
path = CodeEntropyRunner.create_job_folder()
14+
15+
assert path == os.path.join("/cwd", "job001")
16+
mock_makedirs.assert_called_once()
17+
18+
19+
def test_create_job_folder_existing_creates_next():
20+
with (
21+
patch("os.getcwd", return_value="/cwd"),
22+
patch("os.listdir", return_value=["job001", "job002"]),
23+
patch("os.makedirs") as mock_makedirs,
24+
):
25+
path = CodeEntropyRunner.create_job_folder()
26+
27+
assert path == os.path.join("/cwd", "job003")
28+
mock_makedirs.assert_called_once()
29+
30+
31+
def test_create_job_folder_ignores_invalid_names():
32+
with (
33+
patch("os.getcwd", return_value="/cwd"),
34+
patch("os.listdir", return_value=["job001", "abc", "job002"]),
35+
patch("os.makedirs") as _,
36+
):
37+
path = CodeEntropyRunner.create_job_folder()
38+
39+
assert path == os.path.join("/cwd", "job003")
40+
41+
42+
def test_create_job_folder_skips_value_error_suffix():
43+
# jobABC triggers int("ABC") -> ValueError -> continue
44+
with (
45+
patch("os.getcwd", return_value="/cwd"),
46+
patch("os.listdir", return_value=["jobABC", "job001"]),
47+
patch("os.makedirs"),
48+
):
49+
path = CodeEntropyRunner.create_job_folder()
50+
51+
assert path == os.path.join("/cwd", "job002")
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from io import StringIO
2+
from types import SimpleNamespace
3+
from unittest.mock import patch
4+
5+
from rich.console import Console
6+
7+
8+
def test_print_args_table_prints_all_args(runner):
9+
args = SimpleNamespace(alpha=1, beta="two")
10+
11+
buf = StringIO()
12+
test_console = Console(file=buf, force_terminal=False, width=120)
13+
14+
with patch("CodeEntropy.config.runtime.console", test_console):
15+
runner.print_args_table(args)
16+
17+
out = buf.getvalue()
18+
assert "Run Configuration" in out
19+
assert "alpha" in out
20+
assert "1" in out
21+
assert "beta" in out
22+
assert "two" in out
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import pytest
2+
3+
from CodeEntropy.config.runtime import CodeEntropyRunner
4+
5+
6+
class Args:
7+
def __init__(self, **kwargs):
8+
for k, v in kwargs.items():
9+
setattr(self, k, v)
10+
11+
12+
def test_validate_required_args_missing_traj_raises():
13+
args = Args(top_traj_file=None, selection_string="all")
14+
15+
with pytest.raises(ValueError):
16+
CodeEntropyRunner._validate_required_args(args)
17+
18+
19+
def test_validate_required_args_missing_selection_raises():
20+
args = Args(top_traj_file=["a"], selection_string=None)
21+
22+
with pytest.raises(ValueError):
23+
CodeEntropyRunner._validate_required_args(args)
24+
25+
26+
def test_validate_required_args_ok():
27+
args = Args(top_traj_file=["a"], selection_string="all")
28+
CodeEntropyRunner._validate_required_args(args)
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
from types import SimpleNamespace
2+
from unittest.mock import MagicMock, patch
3+
4+
import pytest
5+
6+
7+
def test_run_entropy_workflow_warns_and_skips_non_dict_run_config(runner):
8+
# Arrange: mock all collaborators so the method stays unit-level
9+
runner._logging_config = MagicMock()
10+
runner._config_manager = MagicMock()
11+
runner._reporter = MagicMock()
12+
13+
run_logger = MagicMock()
14+
runner._logging_config.configure.return_value = run_logger
15+
16+
runner._config_manager.load_config.return_value = {"bad_run": "not_a_dict"}
17+
18+
parser = MagicMock()
19+
parser.parse_known_args.return_value = (SimpleNamespace(output_file="out.json"), [])
20+
runner._config_manager.build_parser.return_value = parser
21+
22+
runner.show_splash = MagicMock()
23+
24+
# Act
25+
runner.run_entropy_workflow()
26+
27+
# Assert: one behavior only — warning + skip
28+
run_logger.warning.assert_called_once()
29+
runner._config_manager.resolve.assert_not_called()
30+
31+
32+
def test_run_entropy_workflow_raises_when_required_args_missing(runner):
33+
runner._logging_config = MagicMock()
34+
runner._config_manager = MagicMock()
35+
runner._reporter = MagicMock()
36+
37+
runner._logging_config.configure.return_value = MagicMock()
38+
runner.show_splash = MagicMock()
39+
40+
# config contains a valid dict run so it will try to process it
41+
runner._config_manager.load_config.return_value = {"run1": {}}
42+
43+
# parser returns args with missing top_traj_file/selection_string
44+
parser = MagicMock()
45+
args = SimpleNamespace(
46+
output_file="out.json",
47+
verbose=False,
48+
top_traj_file=None,
49+
selection_string=None,
50+
force_file=None,
51+
file_format=None,
52+
kcal_force_units=False,
53+
)
54+
parser.parse_known_args.return_value = (args, [])
55+
runner._config_manager.build_parser.return_value = parser
56+
57+
# resolve returns same args (still missing required)
58+
runner._config_manager.resolve.return_value = args
59+
60+
with pytest.raises(ValueError):
61+
runner.run_entropy_workflow()
62+
63+
64+
def test_run_entropy_workflow_happy_path_calls_execute_once(runner):
65+
# Mock collaborators
66+
runner._logging_config = MagicMock()
67+
runner._config_manager = MagicMock()
68+
runner._reporter = MagicMock()
69+
runner.show_splash = MagicMock()
70+
runner.print_args_table = MagicMock()
71+
72+
run_logger = MagicMock()
73+
runner._logging_config.configure.return_value = run_logger
74+
75+
# One valid run config dict (so it doesn't hit the "warning+continue" branch)
76+
runner._config_manager.load_config.return_value = {"run1": {}}
77+
78+
# CLI args (must satisfy required args)
79+
args = SimpleNamespace(
80+
output_file="out.json",
81+
verbose=False,
82+
top_traj_file=["top.tpr", "traj.trr"],
83+
selection_string="all",
84+
force_file=None,
85+
file_format=None,
86+
kcal_force_units=False,
87+
)
88+
parser = MagicMock()
89+
parser.parse_known_args.return_value = (args, [])
90+
runner._config_manager.build_parser.return_value = parser
91+
92+
# resolve returns the args
93+
runner._config_manager.resolve.return_value = args
94+
95+
# Avoid MDAnalysis/real work: stub universe creation + validation
96+
runner._build_universe = MagicMock(return_value="U")
97+
runner._config_manager.validate_inputs = MagicMock()
98+
99+
# Patch constructors used in the happy path
100+
with (
101+
patch("CodeEntropy.config.runtime.UniverseOperations") as _,
102+
patch("CodeEntropy.config.runtime.MoleculeGrouper") as _,
103+
patch("CodeEntropy.config.runtime.ConformationStateBuilder") as _,
104+
patch("CodeEntropy.config.runtime.EntropyWorkflow") as EWCls,
105+
):
106+
entropy_instance = MagicMock()
107+
EWCls.return_value = entropy_instance
108+
109+
runner.run_entropy_workflow()
110+
111+
runner.print_args_table.assert_called_once_with(args)
112+
runner._build_universe.assert_called_once()
113+
runner._config_manager.validate_inputs.assert_called_once_with("U", args)
114+
EWCls.assert_called_once()
115+
entropy_instance.execute.assert_called_once()
116+
runner._logging_config.export_console.assert_called_once()
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def test_n_avogadro_property_returns_internal_value(runner):
2+
# uses the runner fixture (tmp folder)
3+
assert runner.N_AVOGADRO == runner._N_AVOGADRO
4+
5+
6+
def test_def_temper_property_returns_internal_value(runner):
7+
assert runner.DEF_TEMPER == runner._DEF_TEMPER
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
from io import StringIO
2+
from unittest.mock import patch
3+
4+
from rich.console import Console
5+
6+
7+
def test_show_splash_with_citation(runner):
8+
citation = {
9+
"title": "TestProject",
10+
"version": "1.0",
11+
"date-released": "2025-01-01",
12+
"url": "https://example.com",
13+
"abstract": "This is a test abstract.",
14+
"authors": [{"given-names": "Alice", "family-names": "Smith"}],
15+
}
16+
17+
buf = StringIO()
18+
console = Console(file=buf, force_terminal=False, width=120)
19+
20+
with (
21+
patch.object(runner, "load_citation_data", return_value=citation),
22+
patch("CodeEntropy.config.runtime.console", console),
23+
):
24+
runner.show_splash()
25+
26+
out = buf.getvalue()
27+
28+
assert "Welcome to CodeEntropy" in out
29+
assert "Version 1.0" in out
30+
assert "2025-01-01" in out
31+
assert "https://example.com" in out
32+
assert "This is a test abstract." in out
33+
assert "Alice Smith" in out
34+
35+
36+
def test_show_splash_without_citation(runner):
37+
buf = StringIO()
38+
console = Console(file=buf, force_terminal=False)
39+
40+
with (
41+
patch.object(runner, "load_citation_data", return_value=None),
42+
patch("CodeEntropy.config.runtime.console", console),
43+
):
44+
runner.show_splash()
45+
46+
assert "Welcome to CodeEntropy" in buf.getvalue()
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
def test_change_lambda_units(runner):
2+
assert runner.change_lambda_units(2.0) == 2.0 * 1e29 / runner.N_AVOGADRO
3+
4+
5+
def test_get_kt2j(runner):
6+
assert runner.get_KT2J(298.0) == 4.11e-21 * 298.0 / runner.DEF_TEMPER

0 commit comments

Comments
 (0)