| 1 |
import argparse |
| 2 |
import contextlib |
| 3 |
from io import StringIO |
| 4 |
import json |
| 5 |
import logging |
| 6 |
import os |
| 7 |
import tempfile |
| 8 |
from typing import Any, Dict, Optional |
| 9 |
import unittest |
| 10 |
from unittest.mock import mock_open, patch |
| 11 |
import pytest |
| 12 |
from con_duct._constants import __schema_version__ |
| 13 |
from con_duct._formatter import SummaryFormatter |
| 14 |
from con_duct.ls import ( |
| 15 |
MINIMUM_SCHEMA_VERSION, |
| 16 |
_flatten_dict, |
| 17 |
_restrict_row, |
| 18 |
ensure_compliant_schema, |
| 19 |
load_duct_runs, |
| 20 |
ls, |
| 21 |
process_run_data, |
| 22 |
) |
| 23 |
|
| 24 |
|
| 25 |
def test_load_duct_runs_sanity() -> None: |
| 26 |
mock_json = json.dumps( |
| 27 |
{"schema_version": "0.2.1", "prefix": "/test/path_", "command": "echo hello"} |
| 28 |
) |
| 29 |
with patch("builtins.open", mock_open(read_data=mock_json)): |
| 30 |
result = load_duct_runs(["/test/path_info.json"]) |
| 31 |
assert len(result) == 1 |
| 32 |
assert result[0]["prefix"] == "/test/path_" |
| 33 |
|
| 34 |
|
| 35 |
def test_load_duct_runs_skips_unsupported_schema() -> None: |
| 36 |
mock_json = json.dumps( |
| 37 |
{"schema_version": "0.1.1", "prefix": "/test/path_", "command": "echo hello"} |
| 38 |
) |
| 39 |
with patch("builtins.open", mock_open(read_data=mock_json)): |
| 40 |
result = load_duct_runs(["/test/path_info.json"]) |
| 41 |
assert len(result) == 0 |
| 42 |
|
| 43 |
|
| 44 |
def test_load_duct_runs_uses_filenames_not_stored_prefix() -> None: |
| 45 |
mock_json = json.dumps( |
| 46 |
{ |
| 47 |
"schema_version": "0.2.1", |
| 48 |
"prefix": "/test/not_anymore_", |
| 49 |
"command": "echo hello", |
| 50 |
} |
| 51 |
) |
| 52 |
with patch("builtins.open", mock_open(read_data=mock_json)): |
| 53 |
result = load_duct_runs(["/actual_filepath_info.json"]) |
| 54 |
assert len(result) == 1 |
| 55 |
assert result[0]["prefix"] == "/actual_filepath_" |
| 56 |
|
| 57 |
|
| 58 |
def test_flatten_dict() -> None: |
| 59 |
nested = {"a": {"b": 1, "c": 2}, "d": 3} |
| 60 |
result = _flatten_dict(nested) |
| 61 |
assert result == {"b": 1, "c": 2, "d": 3} |
| 62 |
|
| 63 |
|
| 64 |
def test_restrict_row() -> None: |
| 65 |
row = {"prefix": "/test/path", "exit_code": 0, "extra": "ignore"} |
| 66 |
fields = ["exit_code"] |
| 67 |
result = _restrict_row(fields, row) |
| 68 |
assert "prefix" in result |
| 69 |
assert "exit_code" in result |
| 70 |
assert "extra" not in result |
| 71 |
|
| 72 |
|
| 73 |
def test_process_run_data() -> None: |
| 74 |
run_data = [ |
| 75 |
{ |
| 76 |
"prefix": "/test/path", |
| 77 |
"exit_code": 0, |
| 78 |
"wall_clock_time": 0.12345678, |
| 79 |
} |
| 80 |
] |
| 81 |
formatter = SummaryFormatter(enable_colors=False) |
| 82 |
result = process_run_data(run_data, ["wall_clock_time"], formatter) |
| 83 |
assert isinstance(result, list) |
| 84 |
assert result[0]["prefix"] == "/test/path" |
| 85 |
assert "exit_code" not in result[0] |
| 86 |
assert result[0]["wall_clock_time"] == "0.123 sec" |
| 87 |
|
| 88 |
|
| 89 |
def test_ensure_compliant_schema_noop_for_current_version() -> None: |
| 90 |
info: Dict[str, Any] = { |
| 91 |
"schema_version": __schema_version__, |
| 92 |
"execution_summary": {}, |
| 93 |
} |
| 94 |
ensure_compliant_schema(info) |
| 95 |
assert "working_directory" not in info["execution_summary"] |
| 96 |
|
| 97 |
|
| 98 |
def test_ensure_compliant_schema_adds_field_for_old_version() -> None: |
| 99 |
info: Dict[str, Any] = {"schema_version": "0.2.0", "execution_summary": {}} |
| 100 |
ensure_compliant_schema(info) |
| 101 |
assert info["execution_summary"]["working_directory"] == "" |
| 102 |
assert info["message"] == "" |
| 103 |
|
| 104 |
|
| 105 |
def test_ensure_compliant_schema_ignores_unexpected_future_version() -> None: |
| 106 |
info: Dict[str, Any] = {"schema_version": "99.0.0", "execution_summary": {}} |
| 107 |
ensure_compliant_schema(info) |
| 108 |
assert "working_directory" not in info["execution_summary"] |
| 109 |
|
| 110 |
|
| 111 |
def test_load_duct_runs_handles_empty_json_files( |
| 112 |
caplog: pytest.LogCaptureFixture, |
| 113 |
) -> None: |
| 114 |
"""Test desired behavior: empty JSON files produce debug logs and are skipped.""" |
| 115 |
with patch("builtins.open", mock_open(read_data="")): |
| 116 |
with caplog.at_level(logging.DEBUG): |
| 117 |
result = load_duct_runs(["/test/empty_info.json"]) |
| 118 |
|
| 119 |
|
| 120 |
assert len(result) == 0 |
| 121 |
|
| 122 |
assert len([r for r in caplog.records if r.levelname == "DEBUG"]) == 1 |
| 123 |
assert not any(r for r in caplog.records if r.levelname == "WARNING") |
| 124 |
assert "Skipping empty file" in caplog.text |
| 125 |
|
| 126 |
|
| 127 |
def test_load_duct_runs_handles_invalid_json_files( |
| 128 |
caplog: pytest.LogCaptureFixture, |
| 129 |
) -> None: |
| 130 |
"""Test current behavior: invalid JSON files produce warnings and are skipped.""" |
| 131 |
with patch("builtins.open", mock_open(read_data="not json at all")): |
| 132 |
with caplog.at_level(logging.WARNING): |
| 133 |
result = load_duct_runs(["/test/invalid_info.json"]) |
| 134 |
|
| 135 |
assert len(result) == 0 |
| 136 |
assert len(caplog.records) == 1 |
| 137 |
assert "Failed to load file" in caplog.text |
| 138 |
|
| 139 |
|
| 140 |
def test_load_duct_runs_mixed_empty_and_valid_files( |
| 141 |
caplog: pytest.LogCaptureFixture, |
| 142 |
) -> None: |
| 143 |
"""Test behavior with mix of empty and valid JSON files.""" |
| 144 |
valid_json = json.dumps( |
| 145 |
{"schema_version": "0.2.1", "prefix": "/test/path_", "command": "echo hello"} |
| 146 |
) |
| 147 |
|
| 148 |
def side_effect(filename: str) -> Any: |
| 149 |
if "empty" in filename: |
| 150 |
return mock_open(read_data="")() |
| 151 |
else: |
| 152 |
return mock_open(read_data=valid_json)() |
| 153 |
|
| 154 |
with patch("builtins.open", side_effect=side_effect): |
| 155 |
with caplog.at_level(logging.DEBUG): |
| 156 |
result = load_duct_runs(["/test/empty_info.json", "/test/valid_info.json"]) |
| 157 |
|
| 158 |
|
| 159 |
assert len(result) == 1 |
| 160 |
assert result[0]["prefix"] == "/test/valid_" |
| 161 |
|
| 162 |
assert len([r for r in caplog.records if r.levelname == "DEBUG"]) == 1 |
| 163 |
assert not any(r for r in caplog.records if r.levelname == "WARNING") |
| 164 |
assert "Skipping empty file" in caplog.text |
| 165 |
|
| 166 |
|
| 167 |
class TestLS(unittest.TestCase): |
| 168 |
def setUp(self) -> None: |
| 169 |
"""Create a temporary directory and test files.""" |
| 170 |
self.temp_dir = tempfile.TemporaryDirectory() |
| 171 |
self.old_cwd = os.getcwd() |
| 172 |
os.chdir(self.temp_dir.name) |
| 173 |
self.files = { |
| 174 |
"file1_info.json": { |
| 175 |
"schema_version": MINIMUM_SCHEMA_VERSION, |
| 176 |
"execution_summary": {}, |
| 177 |
"prefix": "test1", |
| 178 |
"filter_this": "yes", |
| 179 |
}, |
| 180 |
"file2_info.json": { |
| 181 |
"schema_version": MINIMUM_SCHEMA_VERSION, |
| 182 |
"execution_summary": {}, |
| 183 |
"prefix": "test2", |
| 184 |
"filter_this": "no", |
| 185 |
}, |
| 186 |
"file3_info.json": { |
| 187 |
"schema_version": "0.1.0", |
| 188 |
"execution_summary": {}, |
| 189 |
"prefix": "old_version", |
| 190 |
}, |
| 191 |
"not_matching.json": { |
| 192 |
"schema_version": MINIMUM_SCHEMA_VERSION, |
| 193 |
"execution_summary": {}, |
| 194 |
"prefix": "no_match", |
| 195 |
}, |
| 196 |
".duct/logs/default_logpath_info.json": { |
| 197 |
"schema_version": MINIMUM_SCHEMA_VERSION, |
| 198 |
"execution_summary": {}, |
| 199 |
"prefix": "default_file1", |
| 200 |
}, |
| 201 |
} |
| 202 |
for filename, content in self.files.items(): |
| 203 |
full_path = os.path.join(self.temp_dir.name, filename) |
| 204 |
os.makedirs(os.path.dirname(full_path), exist_ok=True) |
| 205 |
with open(full_path, "w") as f: |
| 206 |
json.dump(content, f) |
| 207 |
|
| 208 |
def tearDown(self) -> None: |
| 209 |
"""Clean up the temporary directory.""" |
| 210 |
os.chdir(self.old_cwd) |
| 211 |
self.temp_dir.cleanup() |
| 212 |
|
| 213 |
def _run_ls( |
| 214 |
self, paths: list[str], fmt: str, args: Optional[argparse.Namespace] = None |
| 215 |
) -> str: |
| 216 |
"""Helper function to run ls() and capture stdout.""" |
| 217 |
if args is None: |
| 218 |
args = argparse.Namespace( |
| 219 |
paths=[os.path.join(self.temp_dir.name, path) for path in paths], |
| 220 |
colors=False, |
| 221 |
fields=["prefix", "schema_version"], |
| 222 |
eval_filter=None, |
| 223 |
format=fmt, |
| 224 |
func=ls, |
| 225 |
reverse=False, |
| 226 |
) |
| 227 |
buf = StringIO() |
| 228 |
with contextlib.redirect_stdout(buf): |
| 229 |
exit_code = ls(args) |
| 230 |
assert exit_code == 0 |
| 231 |
return buf.getvalue().strip() |
| 232 |
|
| 233 |
def test_ls_sanity(self) -> None: |
| 234 |
"""Basic sanity test to ensure ls() runs without crashing.""" |
| 235 |
just_file1 = ["file1_info.json"] |
| 236 |
result = self._run_ls(just_file1, "summaries") |
| 237 |
|
| 238 |
assert "Prefix:" in result |
| 239 |
prefixes = [ |
| 240 |
line.split(":", 1)[1].strip() |
| 241 |
for line in result.splitlines() |
| 242 |
if line.startswith("Prefix:") |
| 243 |
] |
| 244 |
assert len(prefixes) == 1 |
| 245 |
assert any("file1" in p for p in prefixes) |
| 246 |
|
| 247 |
def test_ls_with_filter(self) -> None: |
| 248 |
"""Basic sanity test to ensure ls() runs without crashing.""" |
| 249 |
paths = ["file1_info.json", "file2_info.json"] |
| 250 |
args = argparse.Namespace( |
| 251 |
paths=[os.path.join(self.temp_dir.name, path) for path in paths], |
| 252 |
colors=False, |
| 253 |
fields=["prefix", "schema_version"], |
| 254 |
eval_filter="filter_this=='yes'", |
| 255 |
format="summaries", |
| 256 |
func=ls, |
| 257 |
reverse=False, |
| 258 |
) |
| 259 |
result = self._run_ls(paths, "summaries", args) |
| 260 |
|
| 261 |
assert "Prefix:" in result |
| 262 |
prefixes = [ |
| 263 |
line.split(":", 1)[1].strip() |
| 264 |
for line in result.splitlines() |
| 265 |
if line.startswith("Prefix:") |
| 266 |
] |
| 267 |
assert len(prefixes) == 1 |
| 268 |
assert any("file1" in p for p in prefixes) |
| 269 |
|
| 270 |
assert "file2" not in result |
| 271 |
|
| 272 |
def test_ls_no_pos_args(self) -> None: |
| 273 |
result = self._run_ls([], "summaries") |
| 274 |
|
| 275 |
assert "Prefix:" in result |
| 276 |
prefixes = [ |
| 277 |
line.split(":", 1)[1].strip() |
| 278 |
for line in result.splitlines() |
| 279 |
if line.startswith("Prefix:") |
| 280 |
] |
| 281 |
assert len(prefixes) == 1 |
| 282 |
assert any("default_logpath" in p for p in prefixes) |
| 283 |
|
| 284 |
assert "file1" not in result |
| 285 |
assert "file2" not in result |
| 286 |
assert "file3" not in result |
| 287 |
assert "not_matching.json" not in result |
| 288 |
|
| 289 |
def test_ls_multiple_paths(self) -> None: |
| 290 |
"""Basic sanity test to ensure ls() runs without crashing.""" |
| 291 |
files_1_and_2 = ["file1_info.json", "file2_info.json"] |
| 292 |
result = self._run_ls(files_1_and_2, "summaries") |
| 293 |
|
| 294 |
assert "Prefix:" in result |
| 295 |
prefixes = [ |
| 296 |
line.split(":", 1)[1].strip() |
| 297 |
for line in result.splitlines() |
| 298 |
if line.startswith("Prefix:") |
| 299 |
] |
| 300 |
assert len(prefixes) == 2 |
| 301 |
assert any("file1" in p for p in prefixes) |
| 302 |
assert any("file2" in p for p in prefixes) |
| 303 |
|
| 304 |
def test_ls_ignore_old_schema(self) -> None: |
| 305 |
"""Basic sanity test to ensure ls() runs without crashing.""" |
| 306 |
files_1_2_3 = ["file1_info.json", "file2_info.json", "file3_info.json"] |
| 307 |
result = self._run_ls(files_1_2_3, "summaries") |
| 308 |
|
| 309 |
assert "Prefix:" in result |
| 310 |
prefixes = [ |
| 311 |
line.split(":", 1)[1].strip() |
| 312 |
for line in result.splitlines() |
| 313 |
if line.startswith("Prefix:") |
| 314 |
] |
| 315 |
assert len(prefixes) == 2 |
| 316 |
assert any("file1" in p for p in prefixes) |
| 317 |
assert any("file2" in p for p in prefixes) |
| 318 |
|
| 319 |
assert "file3" not in result |
| 320 |
|
| 321 |
def test_ls_ignore_non_infojson(self) -> None: |
| 322 |
"""Basic sanity test to ensure ls() runs without crashing.""" |
| 323 |
all_files = ["file1_info.json", "file2_info.json", "not_matching.json"] |
| 324 |
result = self._run_ls(all_files, "summaries") |
| 325 |
|
| 326 |
assert "Prefix:" in result |
| 327 |
prefixes = [ |
| 328 |
line.split(":", 1)[1].strip() |
| 329 |
for line in result.splitlines() |
| 330 |
if line.startswith("Prefix:") |
| 331 |
] |
| 332 |
assert len(prefixes) == 2 |
| 333 |
assert any("file1" in p for p in prefixes) |
| 334 |
assert any("file2" in p for p in prefixes) |
| 335 |
|
| 336 |
assert "not_matching.json" not in result |
| 337 |
|
| 338 |
def test_ls_json_output(self) -> None: |
| 339 |
"""Test JSON output format.""" |
| 340 |
result = self._run_ls(["file1_info.json"], "json") |
| 341 |
parsed = json.loads(result) |
| 342 |
assert len(parsed) == 1 |
| 343 |
assert "prefix" in parsed[0] |
| 344 |
|
| 345 |
def test_ls_json_pp_output(self) -> None: |
| 346 |
"""Test pretty-printed JSON output format.""" |
| 347 |
result = self._run_ls(["file1_info.json"], "json_pp") |
| 348 |
parsed = json.loads(result) |
| 349 |
assert len(parsed) == 1 |
| 350 |
assert "prefix" in parsed[0] |
| 351 |
|
| 352 |
def test_ls_yaml_output(self) -> None: |
| 353 |
"""Test YAML output format.""" |
| 354 |
yaml = pytest.importorskip("yaml") |
| 355 |
result = self._run_ls(["file1_info.json"], "yaml") |
| 356 |
parsed = yaml.safe_load(result) |
| 357 |
assert len(parsed) == 1 |
| 358 |
assert "prefix" in parsed[0] |
| 359 |
|
| 360 |
def test_ls_pyout_output(self) -> None: |
| 361 |
"""Test pyout output format.""" |
| 362 |
pytest.importorskip("pyout") |
| 363 |
result = self._run_ls(["file1_info.json"], "pyout") |
| 364 |
|
| 365 |
assert "PREFIX" in result |
| 366 |
assert os.path.join(self.temp_dir.name, "file1_") in result |
| 367 |
|
| 368 |
def test_ls_reverse(self) -> None: |
| 369 |
"""Test --reverse flag lists entries in reverse order.""" |
| 370 |
paths = ["file1_info.json", "file2_info.json"] |
| 371 |
|
| 372 |
|
| 373 |
result_normal = self._run_ls(paths, "json") |
| 374 |
parsed_normal = json.loads(result_normal) |
| 375 |
prefixes_normal = [row["prefix"] for row in parsed_normal] |
| 376 |
|
| 377 |
|
| 378 |
args = argparse.Namespace( |
| 379 |
paths=[os.path.join(self.temp_dir.name, path) for path in paths], |
| 380 |
colors=False, |
| 381 |
fields=["prefix", "schema_version"], |
| 382 |
eval_filter=None, |
| 383 |
format="json", |
| 384 |
func=ls, |
| 385 |
reverse=True, |
| 386 |
) |
| 387 |
result_reversed = self._run_ls(paths, "json", args) |
| 388 |
parsed_reversed = json.loads(result_reversed) |
| 389 |
prefixes_reversed = [row["prefix"] for row in parsed_reversed] |
| 390 |
|
| 391 |
assert prefixes_reversed == list(reversed(prefixes_normal)) |