You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@juneau.apache.org by ja...@apache.org on 2026/10/17 18:14:03 UTC
(juneau) branch master updated: juneau-run console: pytest bar counts test files, equal-width wrapped lines, expected test total from history, and steadier rounded time estimates. KeychainSecretStore.store sends its command to security -i on stdin, so a JVM with a terminal no longer hangs on a password prompt.
This is an automated email from the ASF dual-hosted git repository.
jamesbognar pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/juneau.git
The following commit(s) were added to refs/heads/master by this push:
new 804b03b8ee juneau-run console: pytest bar counts test files, equal-width wrapped lines, expected test total from history, and steadier rounded time estimates. KeychainSecretStore.store sends its command to security -i on stdin, so a JVM with a terminal no longer hangs on a password prompt.
804b03b8ee is described below
commit 804b03b8eeab5580301a10d55deee103da1fa4df
Author: James Bognar <ja...@apache.org>
AuthorDate: Sat Oct 17 14:13:57 2026 -0400
juneau-run console: pytest bar counts test files, equal-width wrapped lines, expected test total from history, and steadier rounded time estimates. KeychainSecretStore.store sends its command to security -i on stdin, so a JVM with a terminal no longer hangs on a password prompt.
---
juneau-run/src/main/python/juneau_run.py | 99 +++++++++++++++--
.../main/python/pytest_plugin/juneau_run_pytest.py | 20 +++-
juneau-run/src/test/python/test_estimate.py | 15 +++
juneau-run/src/test/python/test_progress_parser.py | 57 ++++++++++
juneau-run/src/test/python/test_render.py | 71 +++++++++++-
juneau-run/src/test/python/test_session_plan.py | 10 +-
.../secret/macos/keychain/KeychainSecretStore.java | 72 ++++++++----
.../macos/keychain/KeychainSecretStore_Test.java | 123 ++++++++++++++++++---
8 files changed, 408 insertions(+), 59 deletions(-)
diff --git a/juneau-run/src/main/python/juneau_run.py b/juneau-run/src/main/python/juneau_run.py
index 7047b80522..4e7a716269 100644
--- a/juneau-run/src/main/python/juneau_run.py
+++ b/juneau-run/src/main/python/juneau_run.py
@@ -385,7 +385,7 @@ def fmt_elapsed(ms):
return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
-Estimate = collections.namedtuple("Estimate", "wall_s units rate runs")
+Estimate = collections.namedtuple("Estimate", "wall_s units rate runs tests", defaults=(None,))
def _median(xs):
@@ -403,10 +403,12 @@ def estimate_from(records, sig):
if not use:
return None
withunits = [r for r in use if (r.get("units") or {}).get("total")]
+ withtests = [r for r in use if isinstance(r.get("tests"), (int, float)) and r["tests"] > 0]
return Estimate(_median([r["wall_s"] for r in use]),
_median([r["units"]["total"] for r in withunits]) if withunits else None,
_median([r["wall_s"] / r["units"]["total"] for r in withunits]) if withunits else None,
- len(use))
+ len(use),
+ _median([r["tests"] for r in withtests]) if withtests else None)
def eta_figures(e, k, n, est):
@@ -437,6 +439,29 @@ def eta_figures(e, k, n, est):
return None, None, False
+def _step_for(seconds):
+ """The coarseness the displayed estimates round to: 5s under a minute, 15s under ten, 30s above."""
+ return 5 if seconds < 60 else 15 if seconds < 600 else 30
+
+
+def round_estimate(seconds, floor=0):
+ """`seconds` rounded to its _step_for step, and above `floor` (the elapsed time) so a shown total never trails it."""
+ step = _step_for(seconds)
+ rounded = int(seconds / step + 0.5) * step
+ return rounded if rounded > floor else (int(floor // step) + 1) * step
+
+
+def damp_total(shown, new, e, rounded=True):
+ """The estimated total to display (seconds): the one already `shown` is kept until `new` differs from it by more
+ than max(15s, 10%) or the elapsed time `e` reaches it; a replacement is rounded (see round_estimate) unless
+ `rounded` is off. None when `new` is None."""
+ if new is None:
+ return None
+ if shown is not None and e < shown and abs(new - shown) <= max(15, 0.1 * shown):
+ return shown
+ return round_estimate(new, e) if rounded else new
+
+
def timer_text(e, total):
"""Elapsed seconds `e` as M:SS, followed by ` / ~M:SS` when an estimated total is known."""
return fmt_elapsed(e * 1000) + (" / ~" + fmt_elapsed(total * 1000) if total else "")
@@ -507,11 +532,13 @@ def _totals(t):
return (t["total"], t["fail"], t["err"], t["skip"])
-def fmt_totals(totals, tests_mode=False):
+def fmt_totals(totals, tests_mode=False, expected=None):
+ """The totals text; `expected` (history's median test count) shows as `41,200 / ~83,000 tests` until the count passes it."""
if not totals or not totals[0]:
return "no tests run" if tests_mode else ""
total, fail, err, _ = totals
- return f"{total:,} tests" + (f", {fail + err} failed" if fail + err else "")
+ of = f" / ~{round(expected):,}" if expected and total < expected else ""
+ return f"{total:,}{of} tests" + (f", {fail + err} failed" if fail + err else "")
def format_final(status, ms, failed_title, full_log):
@@ -604,6 +631,7 @@ class _Row:
self.units_dropped = 0 # tests-mode modules that ran no tests, taken out of units_total (see _drop_unit)
self.progress = None # live progress text from the tool's own output; shown on the running row only
self.estimate = None # the Estimate from history, when there is one (spec 5.1)
+ self.shown_total = None # the estimated total last displayed, held steady by damp_total
@property
def running(self):
@@ -644,6 +672,7 @@ class Board:
self.aliases = {} # a run_tool sub-row's step id -> its parent row's id (parent=, release.py)
self.setup = None # the run's one Setup row (pom modules), owned by the first Maven row that has poms
self.plan = None # the planned top-level step ids, in order (spec 6), or None
+ self.shown_end = None # the Overall figure's projected end (session seconds) last displayed, held by damp_total
self.plan_estimates = {} # planned step id -> history wall_s or None, asked of the estimator once per plan
self.session_t0 = self.t0 # when the session event arrived (the Overall figure's E)
@@ -734,13 +763,20 @@ class Board:
elif r.running:
e = now - r.t0
_, total, _ = eta_figures(e, r.units_done, r.units_total, r.estimate)
+ total = r.shown_total = damp_total(r.shown_total, total, e)
if total is None and r.estimate is not None:
total = max(r.estimate.wall_s, e) # overran its history: nothing left to add
steps.append((sid, "running", r.estimate.wall_s if r.estimate else None,
(total, e) if total is not None else None))
elif r.status != "skip":
steps.append((sid, "done", None, None))
- return overall_figures(now - self.session_t0, steps)
+ o = overall_figures(now - self.session_t0, steps)
+ if o is None or o.remaining <= 0:
+ return o
+ elapsed = now - self.session_t0 # damp the projected end like a row's total, then show what is left of it
+ self.shown_end = damp_total(self.shown_end, elapsed + o.remaining, elapsed, rounded=False)
+ left = max(self.shown_end - elapsed, 0)
+ return o._replace(remaining=round_estimate(left) if left > 0 else left)
def _on_step_start(self, f):
parent = self.rows.get(f.get("parent"))
@@ -1056,11 +1092,13 @@ def row_cells(row, glyphs, now, pending=False):
elapsed = fmt_elapsed(ms) if ms >= 1000 else ""
if row.running and row.estimate is not None:
pct, total, approx = eta_figures(ms / 1000, row.units_done, row.units_total, row.estimate)
+ total = row.shown_total = damp_total(row.shown_total, total, ms / 1000)
if pct is not None and ms >= 1000:
parts.append(("~" if approx else "") + f"{pct}%")
if elapsed:
elapsed = timer_text(ms / 1000, total)
- text = row.summary if row.summary is not None else fmt_totals(row.totals, row.tests_mode and not row.running)
+ expected = row.estimate.tests if row.running and row.estimate is not None else None
+ text = row.summary if row.summary is not None else fmt_totals(row.totals, row.tests_mode and not row.running, expected)
if text:
parts.append(text)
return cells, " ".join(parts), elapsed
@@ -1250,7 +1288,7 @@ def _fit_row(label, cells, rest, elapsed, cols, wrap=False):
room = cols - (len(elapsed) + 2 if elapsed else 0) - _vlen(label + " " + rest)
if wrap and room >= 1:
indent = _vlen(label) + 2
- per = max(1, cols - indent)
+ per = room # every line holds as many cells as the first
first, more = cells[:room], cells[room:]
lines = [_fit(label + " " + "".join(first) + " " + rest, elapsed, cols)]
lines += [" " * indent + "".join(more[i:i + per]) for i in range(0, len(more), per)]
@@ -2870,6 +2908,12 @@ class PytestParser(Parser):
self.n = 0
self.failed = self.errors = self.skipped = 0
self.index = OrderedDict() # node id -> unit index, bounded: a late marker follows its test at once
+ # File grain (plugin total marker with per-file test counts): one bar unit per test file, finished with its last test
+ self.files = None # file -> tests it holds; None until a total marker carries them
+ self.file_seen = {} # file -> tests finished so far
+ self.file_state = {} # file -> [any failed, all skipped]
+ self.file_cell = {} # finished file -> its bar index
+ self.files_done = 0
def prepare(self, cmd, env, cwd):
existing = None
@@ -2919,6 +2963,13 @@ class PytestParser(Parser):
n = m.get("n")
if isinstance(n, int) and n >= 0:
self.n = n
+ files = m.get("f")
+ if isinstance(files, dict) and files and all(isinstance(v, int) for v in files.values()):
+ changed = self.files is None or len(files) != len(self.files)
+ self.files = files
+ return [("units", self.step_id, len(files), "files")] if changed else []
+ if self.files is not None:
+ return []
return [("units", self.step_id, n, "tests")]
return []
if kind != "test":
@@ -2930,7 +2981,15 @@ class PytestParser(Parser):
if m.get("late"):
self.errors += 1
events = []
- idx = self.index.get(m.get("id"))
+ fname = self._file_of(m.get("id"))
+ if self.files is not None:
+ if fname in self.file_cell:
+ events.append(("unit_fix", self.step_id, self.file_cell[fname], "fail"))
+ elif fname in self.files:
+ self._file_note(fname, "error")
+ idx = None
+ else:
+ idx = self.index.get(m.get("id"))
if idx is not None:
events.append(("unit_fix", self.step_id, idx, "fail"))
events.append(self._tests_event())
@@ -2946,8 +3005,32 @@ class PytestParser(Parser):
self.errors += 1
elif unit == "skip":
self.skipped += 1
+ if self.files is not None:
+ events = [self._tests_event()]
+ fname = self._file_of(m.get("id"))
+ if fname in self.files:
+ self._file_note(fname, outcome)
+ self.file_seen[fname] = self.file_seen.get(fname, 0) + 1
+ if self.file_seen[fname] >= self.files[fname] and fname not in self.file_cell:
+ state = self.file_state[fname]
+ self.file_cell[fname] = self.files_done
+ self.files_done += 1
+ events.insert(0, ("unit", self.step_id, self.files_done,
+ "fail" if state[0] else "skip" if state[1] else "pass"))
+ return events
return [("unit", self.step_id, self.done, unit), self._tests_event()]
+ @staticmethod
+ def _file_of(node_id):
+ return str(node_id).split("::", 1)[0][:400]
+
+ def _file_note(self, fname, outcome):
+ state = self.file_state.setdefault(fname, [False, True])
+ if outcome in ("failed", "error"):
+ state[0] = True
+ if self.OUTCOME.get(outcome) != "skip":
+ state[1] = False
+
def _set_n(self, n):
if n == self.n:
return []
diff --git a/juneau-run/src/main/python/pytest_plugin/juneau_run_pytest.py b/juneau-run/src/main/python/pytest_plugin/juneau_run_pytest.py
index 9cdacdc4e4..d1e1c5c732 100644
--- a/juneau-run/src/main/python/pytest_plugin/juneau_run_pytest.py
+++ b/juneau-run/src/main/python/pytest_plugin/juneau_run_pytest.py
@@ -96,21 +96,33 @@ def pytest_configure(config):
def pytest_collection_finish(session):
if not _worker(session.config):
- _total(session.config, len(session.items))
+ _total(session.config, len(session.items), _file_counts(i.nodeid for i in session.items))
class _XdistHooks:
"""Registered only when xdist is loaded: pytest rejects a plain hook function for an unknown hook name."""
def pytest_xdist_node_collection_finished(self, node, ids):
- _total(node.config, len(ids))
+ _total(node.config, len(ids), _file_counts(ids))
-def _total(config, n):
+def _file_counts(ids):
+ """Tests per test file, keyed by the file part of the node id; the runner draws one bar cell per file."""
+ counts = {}
+ for nid in ids:
+ f = nid.split("::", 1)[0][:400]
+ counts[f] = counts.get(f, 0) + 1
+ return counts
+
+
+def _total(config, n, files=None):
global _total_sent
if n > _total_sent: # once (even for 0), and again only for a larger count (spec 1.1)
_total_sent = n
- _emit(config, {"ev": "total", "n": n})
+ mark = {"ev": "total", "n": n}
+ if files:
+ mark["f"] = files
+ _emit(config, mark)
_durations = {}
diff --git a/juneau-run/src/test/python/test_estimate.py b/juneau-run/src/test/python/test_estimate.py
index e0573deada..5019cee55d 100644
--- a/juneau-run/src/test/python/test_estimate.py
+++ b/juneau-run/src/test/python/test_estimate.py
@@ -108,5 +108,20 @@ class MakeEstimatorTest(unittest.TestCase):
self.assertEqual(est("mvn", "maven", "other").runs, 4) # fewer than 3 like: falls back to all
+class ExpectedTestsTest(unittest.TestCase):
+ def rec(self, tests, **kw):
+ return dict({"ok": True, "complete": True, "wall_s": 10.0, "tests": tests}, **kw)
+
+ def test_median_test_count_of_the_records_used(self):
+ self.assertEqual(jr.estimate_from([self.rec(100), self.rec(300), self.rec(200)], None).tests, 200)
+
+ def test_none_without_test_counts(self):
+ self.assertIsNone(jr.estimate_from([{"ok": True, "complete": True, "wall_s": 5.0}], None).tests)
+
+ def test_prefers_like_for_like_records(self):
+ records = [self.rec(10, sig="a")] + [self.rec(500, sig="b") for _ in range(3)]
+ self.assertEqual(jr.estimate_from(records, "b").tests, 500)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/juneau-run/src/test/python/test_progress_parser.py b/juneau-run/src/test/python/test_progress_parser.py
index 64d935f367..6849452954 100644
--- a/juneau-run/src/test/python/test_progress_parser.py
+++ b/juneau-run/src/test/python/test_progress_parser.py
@@ -141,5 +141,62 @@ class PlaywrightUnitsTest(unittest.TestCase):
self.assertEqual(units(events), [("units", "w", 4, "tests"), ("unit", "w", 1, None), ("unit", "w", 2, None)])
+def total_mark(files):
+ return '##pytest ' + json.dumps({"ev": "total", "n": sum(files.values()), "f": files})
+
+
+def test_mark(outcome, nid, late=False):
+ return '##pytest ' + json.dumps({"ev": "test", "o": outcome, "id": nid, "s": 0.0, **({"late": 1} if late else {})})
+
+
+class FileGrainTest(unittest.TestCase):
+ """With per-file counts in the plugin's total marker, the unit is the test file."""
+
+ def test_total_announces_files_not_tests(self):
+ events = ev(new_parser(), ['##pytest {"ev":"hello","v":1}', total_mark({"a.py": 2, "b.py": 3})])
+ self.assertEqual(units(events), [("units", "p", 2, "files")])
+
+ def test_a_file_finishes_with_its_last_test(self):
+ p = new_parser()
+ events = ev(p, [total_mark({"a.py": 2, "b.py": 1}), test_mark("passed", "a.py::t1"), test_mark("passed", "b.py::t1"),
+ test_mark("passed", "a.py::t2")])
+ self.assertEqual(units(events), [("units", "p", 2, "files"), ("unit", "p", 1, "pass"), ("unit", "p", 2, "pass")])
+ self.assertEqual([e for e in events if e[0] == "tests"][-1], ("tests", "p", 3, 0, 0, 0)) # still counted per test
+
+ def test_a_failed_or_errored_test_fails_its_file(self):
+ events = ev(new_parser(), [total_mark({"a.py": 2, "b.py": 2}),
+ test_mark("passed", "a.py::t1"), test_mark("failed", "a.py::t2"),
+ test_mark("error", "b.py::t1"), test_mark("passed", "b.py::t2")])
+ self.assertEqual([e for e in events if e[0] == "unit"], [("unit", "p", 1, "fail"), ("unit", "p", 2, "fail")])
+
+ def test_a_file_is_skipped_only_when_every_test_skipped(self):
+ events = ev(new_parser(), [total_mark({"a.py": 2, "b.py": 2}),
+ test_mark("skipped", "a.py::t1"), test_mark("xfailed", "a.py::t2"),
+ test_mark("skipped", "b.py::t1"), test_mark("passed", "b.py::t2")])
+ self.assertEqual([e for e in events if e[0] == "unit"], [("unit", "p", 1, "skip"), ("unit", "p", 2, "pass")])
+
+ def test_interleaved_files_finish_in_completion_order(self): # xdist: tests of different files mix
+ events = ev(new_parser(), [total_mark({"a.py": 2, "b.py": 2}),
+ test_mark("passed", "a.py::t1"), test_mark("passed", "b.py::t1"),
+ test_mark("failed", "b.py::t2"), test_mark("passed", "a.py::t2")])
+ self.assertEqual([e for e in events if e[0] == "unit"], [("unit", "p", 1, "fail"), ("unit", "p", 2, "pass")])
+
+ def test_a_late_error_fixes_a_finished_file_and_fails_an_open_one(self):
+ events = ev(new_parser(), [total_mark({"a.py": 1, "b.py": 2}), test_mark("passed", "a.py::t1"),
+ test_mark("error", "a.py::t1", late=True),
+ test_mark("passed", "b.py::t1"), test_mark("error", "b.py::t1", late=True),
+ test_mark("passed", "b.py::t2")])
+ self.assertIn(("unit_fix", "p", 0, "fail"), events)
+ self.assertEqual([e for e in events if e[0] == "unit"][-1], ("unit", "p", 2, "fail"))
+
+ def test_total_without_file_counts_stays_per_test(self): # an older plugin, or the fallback
+ events = ev(new_parser(), ['##pytest {"ev":"total","n":3}', test_mark("passed", "a.py::t1")])
+ self.assertEqual(units(events), [("units", "p", 3, "tests"), ("unit", "p", 1, "pass")])
+
+ def test_scraped_xdist_progress_has_no_file_names_and_stays_per_test(self):
+ events = ev(new_parser(), ["collected 6 items", "..F [ 50%]"])
+ self.assertEqual(units(events)[0], ("units", "p", 6, "tests"))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/juneau-run/src/test/python/test_render.py b/juneau-run/src/test/python/test_render.py
index 6c085ff893..10bd14854d 100644
--- a/juneau-run/src/test/python/test_render.py
+++ b/juneau-run/src/test/python/test_render.py
@@ -575,7 +575,7 @@ class RowEstimateTest(unittest.TestCase):
b.apply("unit", dict(step="s", done=26, outcome="pass"))
cells, rest, elapsed = self.cells(b)
self.assertIn("26/100 26%", rest)
- self.assertEqual(elapsed, "0:26 / ~1:40")
+ self.assertEqual(elapsed, "0:26 / ~1:45")
def test_finished_row_shows_elapsed_only(self):
b = self.board(lambda step, tool, sig=None: self.est)
@@ -603,17 +603,17 @@ class RowEstimateTest(unittest.TestCase):
cells, rest, elapsed = self.cells(b)
label = b.rows["s"].label.ljust(b.width())
wide = jr._fit_row(label, cells, rest, elapsed, 80)
- self.assertTrue(wide.endswith("0:26 / ~1:40"))
+ self.assertTrue(wide.endswith("0:26 / ~1:45"))
narrow = jr._fit_row(label, cells, rest, elapsed, len(label) + len(rest) + 8)
self.assertTrue(narrow.endswith("0:26"), narrow)
- self.assertNotIn("~1:40", narrow)
+ self.assertNotIn("~1:45", narrow)
def test_marked_when_history_driven(self):
b = self.board(lambda step, tool, sig=None: jr.Estimate(wall_s=100.0, units=None, rate=None, runs=5))
self.clock.advance(63)
cells, rest, elapsed = self.cells(b)
self.assertEqual(rest, "~63%")
- self.assertEqual(elapsed, "1:03 / ~1:40")
+ self.assertEqual(elapsed, "1:03 / ~1:45")
def test_no_estimator_matches_today(self):
for estimator in (None, lambda step, tool, sig=None: None):
@@ -1408,5 +1408,68 @@ class RobustnessTest(unittest.TestCase):
self.assertEqual(signal.getsignal(signal.SIGTERM), signal.SIG_DFL)
+class WrapAndExpectedTest(unittest.TestCase):
+ """Equal-width continuation lines and the expected test total."""
+
+ def test_every_line_of_a_wrapped_bar_holds_the_same_number_of_cells(self):
+ line = jr._fit_row("Tests", ["#"] * 50, "50/50", "0:05", 40, wrap=True)
+ lines = line.split("\n")
+ counts = [l.count("#") for l in lines]
+ self.assertGreater(len(lines), 2)
+ self.assertEqual(len(set(counts[:-1])), 1, counts)
+ self.assertLessEqual(counts[-1], counts[0])
+ self.assertEqual(sum(counts), 50)
+
+ def test_expected_total_shows_until_the_count_passes_it(self):
+ self.assertEqual(jr.fmt_totals((41200, 0, 0, 0), expected=83000), "41,200 / ~83,000 tests")
+ self.assertEqual(jr.fmt_totals((83051, 0, 0, 0), expected=83000), "83,051 tests")
+ self.assertEqual(jr.fmt_totals((5, 2, 0, 0), expected=None), "5 tests, 2 failed")
+
+ def test_running_row_shows_expected_tests_and_finished_row_drops_it(self):
+ reset_run_state()
+ self.addCleanup(reset_run_state)
+ clock = Clock()
+ est = jr.Estimate(wall_s=100.0, units=None, rate=None, runs=5, tests=1000)
+ b = jr.Board("actionable", nested=False, full_log=None, clock=clock, estimator=lambda *a: est)
+ b.apply("step_start", dict(id="s", n=1, title="py", parent=None, tool="pytest", sig=""))
+ b.apply("tests", dict(step="s", total=400, fail=0, err=0, skip=0))
+ clock.advance(2)
+ self.assertIn("400 / ~1,000 tests", jr.row_cells(b.rows["s"], jr.PLAIN_GLYPHS, clock())[1])
+ b.apply("step_end", dict(id="s", status="ok", ms=3000))
+ self.assertNotIn("~1,000", jr.row_cells(b.rows["s"], jr.PLAIN_GLYPHS, clock())[1])
+
+ def test_no_history_means_no_expected_total(self):
+ reset_run_state()
+ self.addCleanup(reset_run_state)
+ clock = Clock()
+ b = jr.Board("actionable", nested=False, full_log=None, clock=clock, estimator=lambda *a: None)
+ b.apply("step_start", dict(id="s", n=1, title="py", parent=None, tool="pytest", sig=""))
+ b.apply("tests", dict(step="s", total=400, fail=0, err=0, skip=0))
+ clock.advance(2)
+ self.assertEqual(jr.row_cells(b.rows["s"], jr.PLAIN_GLYPHS, clock())[1], "400 tests")
+
+
+class DampedEstimateTest(unittest.TestCase):
+ def test_rounding_steps(self):
+ self.assertEqual(jr.round_estimate(32), 30)
+ self.assertEqual(jr.round_estimate(100), 105)
+ self.assertEqual(jr.round_estimate(700), 690)
+ self.assertEqual(jr.round_estimate(1000), 990)
+
+ def test_a_rounded_total_stays_above_elapsed(self):
+ self.assertGreater(jr.round_estimate(31, floor=30), 30)
+
+ def test_small_changes_keep_the_shown_total(self):
+ self.assertEqual(jr.damp_total(472, 480, 100), 472)
+ self.assertEqual(jr.damp_total(472, 472 + 47, 100), 472) # within 10%
+ self.assertEqual(jr.damp_total(40, 54, 10), 40) # within 15s
+
+ def test_a_large_change_or_an_overrun_moves_it(self):
+ self.assertEqual(jr.damp_total(472, 600, 100), 600)
+ self.assertEqual(jr.damp_total(100, 105, 100), 105) # elapsed reached the shown total
+ self.assertIsNone(jr.damp_total(100, None, 10))
+ self.assertEqual(jr.damp_total(None, 472, 10), 465)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/juneau-run/src/test/python/test_session_plan.py b/juneau-run/src/test/python/test_session_plan.py
index 5ef1faa843..c8abc86f1f 100644
--- a/juneau-run/src/test/python/test_session_plan.py
+++ b/juneau-run/src/test/python/test_session_plan.py
@@ -90,7 +90,7 @@ class BoardPlanTest(unittest.TestCase):
def test_pending_plan(self):
o = self.board().overall()
- self.assertEqual((o.remaining, o.done, o.total, o.percent), (200, 0, 3, 0))
+ self.assertEqual((o.remaining, o.done, o.total, o.percent), (195, 0, 3, 0))
def test_finished_and_running(self):
b = self.board()
@@ -98,13 +98,13 @@ class BoardPlanTest(unittest.TestCase):
b.apply(*end("a")); b.apply(*start("b")); self.clock.advance(30)
o = b.overall()
self.assertEqual(o.done, 1)
- self.assertEqual(o.remaining, 70 + 40) # b: 100 - 30, c: 40
+ self.assertEqual(o.remaining, 120) # b: 100 - 30, c: 40 = 110, shown on the 15s step
def test_skipped_planned_step_stops_counting(self):
b = self.board()
b.apply(*start("a")); b.apply(*end("a", "skip"))
o = b.overall()
- self.assertEqual((o.total, o.done, o.remaining), (2, 0, 140))
+ self.assertEqual((o.total, o.done, o.remaining), (2, 0, 135)) # 140 on the 15s step
def test_pending_step_passed_over_stops_counting(self):
b = self.board()
@@ -117,7 +117,7 @@ class BoardPlanTest(unittest.TestCase):
b = self.board()
b.apply(*start("x")); self.clock.advance(50); b.apply(*end("x"))
o = b.overall()
- self.assertEqual(o.remaining, 200)
+ self.assertEqual(o.remaining, 195) # 200 on the 15s step
self.assertEqual(o.percent, 20) # 50 / (50 + 200)
def test_missing_history_is_a_lower_bound(self):
@@ -143,7 +143,7 @@ class BoardPlanTest(unittest.TestCase):
r.units_total, r.units_done = 10, 5
self.clock.advance(30) # 5 of 10 units in 30s: ~60s total, 30s left
o = b.overall()
- self.assertEqual(o.remaining, 30 + 100 + 40)
+ self.assertEqual(o.remaining, 165) # 170 on the 15s step
def test_overrun_with_nothing_else_known_has_no_left_time(self):
b = self.board(plan=("a",), hist={"a": 10.0})
diff --git a/juneau-secret-macos-keychain/src/main/java/org/apache/juneau/secret/macos/keychain/KeychainSecretStore.java b/juneau-secret-macos-keychain/src/main/java/org/apache/juneau/secret/macos/keychain/KeychainSecretStore.java
index 232628e428..9420d4910e 100644
--- a/juneau-secret-macos-keychain/src/main/java/org/apache/juneau/secret/macos/keychain/KeychainSecretStore.java
+++ b/juneau-secret-macos-keychain/src/main/java/org/apache/juneau/secret/macos/keychain/KeychainSecretStore.java
@@ -52,15 +52,19 @@ import org.apache.juneau.commons.secret.*;
* absent/no-op, while {@link FailMode#FAIL_CLOSED} (the default) throws.
*
* <p>
- * <b>Secret handling.</b> {@link #store} never places the secret on the {@code security} process's argv: it invokes
- * <c>add-generic-password</c> with a bare, valueless <c>-w</c> (which makes the CLI prompt) and writes the secret,
- * followed by a newline, twice to the child process's stdin — once for the value and once for the CLI's own
- * confirmation re-entry — so the secret is never visible in the process table (e.g. to {@code ps}). Neither
+ * <b>Secret handling.</b> {@link #store} never places the secret on the {@code security} process's argv, and never
+ * relies on the CLI's password prompt (a bare <c>-w</c> makes {@code security} read from the controlling terminal,
+ * <c>/dev/tty</c>, whenever the JVM has one — not from stdin — so it would hang). Instead it runs
+ * <c>security -i</c> (interactive mode, which reads commands from stdin) and writes a single command line to stdin:
+ * <c>add-generic-password -U -a "<i>key</i>" -s "<i>service</i>" -w "<i>secret</i>"</c>. The secret is therefore
+ * never visible in the process table (e.g. to {@code ps}), and no terminal is ever read. Each of the three values is
+ * double-quoted, with only <c>"</c> and <c>\</c> escaped by a preceding backslash (verified against {@code security -i}
+ * for spaces, tabs, single and double quotes, backslashes, shell metacharacters, and non-ASCII text). Neither
* {@link #store} nor {@link #find} materializes the secret as a {@link String}: {@code store} encodes the
* {@code char[]} directly to the stdin byte payload, and {@code find} decodes the retrieved bytes into a
- * {@code char[]}. The value is never logged or {@code toString()}'d by this class. Because the confirmation
- * prompt splits input on newlines, a secret containing {@code '\n'} or {@code '\r'} cannot be delivered this way
- * and is rejected by {@link #store} before any process is started.
+ * {@code char[]}. The value is never logged or {@code toString()}'d by this class. Because the command is
+ * newline-terminated, a key, service, or secret containing {@code '\n'} or {@code '\r'} cannot be delivered this way
+ * (it would end or inject a command) and is rejected by {@link #store} before any process is started.
*
* @since 10.0.0
*/
@@ -140,12 +144,14 @@ public class KeychainSecretStore implements SecretStore {
public void store(String key, char[] secret) {
reqnn("key", key);
reqnn("secret", secret);
+ req(! containsNewline(key), "Argument 'key' must not contain a newline or carriage return character.");
+ req(! containsNewline(service), "The service name must not contain a newline or carriage return character.");
req(! containsNewline(secret), "Argument 'secret' must not contain a newline or carriage return character.");
- var payload = stdinConfirmationPayload(secret);
+ var payload = addCommandPayload(key, secret);
try {
- // A bare, valueless "-w" makes the CLI prompt (twice, for confirmation) on stdin/stderr instead
- // of accepting the password as an argv element, so the secret never appears in the process table.
- var r = run(payload, "add-generic-password", "-U", "-a", key, "-s", service, "-w");
+ // "security -i" reads commands from stdin; a bare "-w" would prompt on /dev/tty (hanging when the JVM has
+ // a terminal), and "-w <secret>" on argv would expose the secret to ps. The command line goes on stdin.
+ var r = run(payload, "-i");
if (r.exit() != 0)
throw backendFailure("add-generic-password", r);
} catch (RuntimeException e) {
@@ -301,34 +307,56 @@ public class KeychainSecretStore implements SecretStore {
return isex("Keychain '%s' failed with exit code %s: %s", subcommand, r.exit(), r.stderr().strip());
}
- private static boolean containsNewline(char[] secret) {
- for (char c : secret)
+ private static boolean containsNewline(String s) {
+ return s.indexOf('\n') >= 0 || s.indexOf('\r') >= 0;
+ }
+
+ private static boolean containsNewline(char[] chars) {
+ for (char c : chars)
if (c == '\n' || c == '\r')
return true;
return false;
}
/**
- * Encodes {@code secret} as UTF-8 and doubles it with a trailing newline after each copy (<c>secret\nsecret\n</c>),
- * matching the value-then-confirmation prompt that <c>security ... -w</c> (with no value) issues on stdin.
- * Built directly from the {@code char[]}, without an intermediate {@link String}.
+ * Builds the <c>security -i</c> stdin payload
+ * <c>add-generic-password -U -a "key" -s "service" -w "secret"\n</c>, double-quoting each value and escaping
+ * <c>"</c> and <c>\</c> with a backslash. The secret is encoded and escaped directly from the {@code char[]},
+ * without an intermediate {@link String}, and the intermediate byte copy is zeroed.
*/
- private static byte[] stdinConfirmationPayload(char[] secret) {
+ private byte[] addCommandPayload(String key, char[] secret) {
+ var head = ("add-generic-password -U -a " + quote(key) + " -s " + quote(service) + " -w \"").getBytes(UTF_8);
var encoded = UTF_8.encode(CharBuffer.wrap(secret));
var secretBytes = new byte[encoded.remaining()];
encoded.get(secretBytes);
+ if (encoded.hasArray())
+ Arrays.fill(encoded.array(), (byte) 0);
try {
- var payload = new byte[(secretBytes.length + 1) * 2];
- System.arraycopy(secretBytes, 0, payload, 0, secretBytes.length);
- payload[secretBytes.length] = '\n';
- System.arraycopy(secretBytes, 0, payload, secretBytes.length + 1, secretBytes.length);
- payload[payload.length - 1] = '\n';
+ var escapes = 0;
+ for (var b : secretBytes)
+ if (b == '"' || b == '\\')
+ escapes++;
+ var payload = new byte[head.length + secretBytes.length + escapes + 2];
+ System.arraycopy(head, 0, payload, 0, head.length);
+ var i = head.length;
+ for (var b : secretBytes) {
+ if (b == '"' || b == '\\')
+ payload[i++] = '\\';
+ payload[i++] = b;
+ }
+ payload[i++] = '"';
+ payload[i] = '\n';
return payload;
} finally {
Arrays.fill(secretBytes, (byte) 0);
}
}
+ /** Double-quotes a non-secret value for <c>security -i</c>, escaping <c>"</c> and <c>\</c>. */
+ private static String quote(String s) {
+ return '"' + s.replace("\\", "\\\\").replace("\"", "\\\"") + '"';
+ }
+
/** Decodes UTF-8 stdout bytes into a char[], dropping a single trailing newline, without an intermediate String. */
private static char[] decodeTrimmed(byte[] bytes) {
var len = bytes.length;
diff --git a/juneau-secret-macos-keychain/src/test/java/org/apache/juneau/secret/macos/keychain/KeychainSecretStore_Test.java b/juneau-secret-macos-keychain/src/test/java/org/apache/juneau/secret/macos/keychain/KeychainSecretStore_Test.java
index 1bf4ba0bc4..80d4fa58af 100644
--- a/juneau-secret-macos-keychain/src/test/java/org/apache/juneau/secret/macos/keychain/KeychainSecretStore_Test.java
+++ b/juneau-secret-macos-keychain/src/test/java/org/apache/juneau/secret/macos/keychain/KeychainSecretStore_Test.java
@@ -36,9 +36,9 @@ import org.junit.jupiter.api.*;
* store's real argument construction and output parsing deterministically on every OS — no
* {@code /usr/bin/security}, no login-keychain mutation, and no GUI unlock/auth prompt. The {@link FailMode} and
* validation tests use a deliberately bad binary path so they also run deterministically on any platform without
- * touching a real keychain. There is intentionally no test against the real {@code security} binary: doing so
- * without risking a hung, unattended GUI prompt on an interactive/locked login keychain would require this store to
- * support targeting an isolated, freshly-created keychain, which is out of scope here.
+ * touching a real keychain. The only test against the real {@code security} binary is {@link #f01_realKeychainRoundTrip},
+ * which mutates the login keychain (a throwaway item, always deleted) and so runs only on macOS, only when
+ * {@code /usr/bin/security} exists, and only when opted in with {@code -Djuneau.keychain.integration=true}.
*/
class KeychainSecretStore_Test {
@@ -63,26 +63,57 @@ class KeychainSecretStore_Test {
@Override
public KeychainSecretStore.Result run(byte[] stdin, String[] args) {
+ // store() runs "security -i" and sends the add-generic-password command line on stdin.
+ if (args.length == 1 && args[0].equals("-i"))
+ return interactive(stdin);
return switch (args[0]) {
- case "add-generic-password" -> addGenericPassword(stdin, args);
case "find-generic-password" -> findGenericPassword(args);
case "delete-generic-password" -> deleteGenericPassword(args);
default -> throw new IllegalArgumentException("Unsupported command: " + args[0]);
};
}
- private KeychainSecretStore.Result addGenericPassword(byte[] stdin, String[] args) {
- // The value and its CLI confirmation re-entry arrive doubled and newline-delimited (see
- // KeychainSecretStore.store's javadoc); both copies must match, mirroring the real prompt.
- var lines = new String(stdin, UTF_8).split("\n", -1);
- var value = lines[0];
- var confirmation = lines[1];
- if (! value.equals(confirmation))
- return new KeychainSecretStore.Result(1, new byte[0], "Password confirmation did not match.");
- entries.put(key(args), value.toCharArray());
+ private KeychainSecretStore.Result interactive(byte[] stdin) {
+ var line = new String(stdin, UTF_8);
+ if (! line.endsWith("\n") || line.indexOf('\n') != line.length() - 1)
+ throw new IllegalArgumentException("Expected exactly one newline-terminated command line.");
+ var args = tokenize(line.substring(0, line.length() - 1));
+ if (! args[0].equals("add-generic-password"))
+ throw new IllegalArgumentException("Unsupported command: " + args[0]);
+ entries.put(key(args), opt(args, "-w").toCharArray());
return new KeychainSecretStore.Result(0, new byte[0], "");
}
+ /** Mirrors the verified {@code security -i} parser: whitespace-separated, double-quoted tokens, backslash escapes the next char. */
+ static String[] tokenize(String line) {
+ var tokens = new ArrayList<String>();
+ var sb = new StringBuilder();
+ var inToken = false;
+ var quoted = false;
+ for (var i = 0; i < line.length(); i++) {
+ var c = line.charAt(i);
+ if (c == '\\') {
+ sb.append(line.charAt(++i));
+ inToken = true;
+ } else if (c == '"') {
+ quoted = ! quoted;
+ inToken = true;
+ } else if (Character.isWhitespace(c) && ! quoted) {
+ if (inToken)
+ tokens.add(sb.toString());
+ sb.setLength(0);
+ inToken = false;
+ } else {
+ sb.append(c);
+ inToken = true;
+ }
+ }
+ assertFalse(quoted, "unterminated quote");
+ if (inToken)
+ tokens.add(sb.toString());
+ return tokens.toArray(new String[0]);
+ }
+
private KeychainSecretStore.Result findGenericPassword(String[] args) {
var value = entries.get(key(args));
if (value == null)
@@ -166,9 +197,10 @@ class KeychainSecretStore_Test {
var argvContent = Files.readString(argvDump.toPath());
assertFalse(argvContent.contains(secret), "secret must not appear in the child process's argv");
+ assertEquals("-i\n", argvContent, "store() must invoke 'security -i' with no other arguments (no bare -w prompt)");
var stdinContent = Files.readString(stdinDump.toPath());
- assertEquals(secret + "\n" + secret + "\n", stdinContent, "secret should be delivered via stdin, doubled for the CLI's confirmation prompt");
+ assertEquals("add-generic-password -U -a \"acct\" -s \"svc\" -w \"" + secret + "\"\n", stdinContent, "command line should be delivered via stdin");
} finally {
argvDump.delete();
stdinDump.delete();
@@ -176,6 +208,30 @@ class KeychainSecretStore_Test {
}
}
+ @Test void a04_quotingEdgeCasesRoundTrip() {
+ var store = new KeychainSecretStore("my svc \"q\" \\", FailMode.FAIL_CLOSED, new FakeKeychain());
+ var values = new String[] {
+ "plain", "a b", "a\"b", "a'b", "a\\b", "a\\\\b", "\\\"", "\"", "'", "a\tb", " lead", "trail ", "#hash",
+ "$x `y` ;|&", "", "\u00e9 \u00fc \u6f22", "-x", "--", "a\\nb", "\"; add-generic-password -a evil -s evil -w \"x"
+ };
+ for (var acct : new String[] {"acct", "my acct", "q\"uo'te\\", "\u00e9"}) {
+ for (var v : values) {
+ store.store(acct, v.toCharArray());
+ assertArrayEquals(v.toCharArray(), store.find(acct).orElseThrow(), "acct=" + acct + " value=" + v);
+ }
+ }
+ }
+
+ @Test void a05_payloadIsOneLineWithExpectedEscaping() {
+ var captured = new byte[1][];
+ var store = new KeychainSecretStore("s\"v\\c", FailMode.FAIL_CLOSED, (stdin, args) -> {
+ captured[0] = stdin.clone();
+ return new KeychainSecretStore.Result(0, new byte[0], "");
+ });
+ store.store("a b", "p\"w\\d 'x'".toCharArray());
+ assertEquals("add-generic-password -U -a \"a b\" -s \"s\\\"v\\\\c\" -w \"p\\\"w\\\\d 'x'\"\n", new String(captured[0], UTF_8));
+ }
+
// -----------------------------------------------------------------------------------------------------------------
// FailMode on an unavailable backend (deterministic via a bad binary path).
// -----------------------------------------------------------------------------------------------------------------
@@ -238,8 +294,8 @@ class KeychainSecretStore_Test {
}
@Test void c05_secretWithNewlineOrCarriageReturnRejectedBeforeAnyProcessStarts() {
- // The stdin-delivered value/confirmation pair (see a03) is newline-delimited, so an embedded '\n' or '\r'
- // in the secret would desynchronize the CLI's confirmation prompt; reject it up front instead.
+ // The stdin-delivered command (see a03) is newline-terminated, so an embedded '\n' or '\r' in the secret
+ // would end or inject a command; reject it up front instead.
var store = unavailable(FailMode.FAIL_CLOSED);
var withNewline = "line1\nline2".toCharArray();
var withCarriageReturn = "line1\rline2".toCharArray();
@@ -247,6 +303,16 @@ class KeychainSecretStore_Test {
assertThrows(IllegalArgumentException.class, () -> store.store("acct", withCarriageReturn));
}
+ @Test void c06_keyOrServiceWithNewlineRejectedBeforeAnyProcessStarts() {
+ // "security -i" reads one command per line, so a newline in the key or service would inject a second command.
+ var secret = "v".toCharArray();
+ var store = unavailable(FailMode.FAIL_OPEN);
+ assertThrows(IllegalArgumentException.class, () -> store.store("a\nb", secret));
+ assertThrows(IllegalArgumentException.class, () -> store.store("a\rb", secret));
+ var badService = new KeychainSecretStore("s\nvc", FailMode.FAIL_OPEN, 5L, "/nonexistent/juneau-not-security");
+ assertThrows(IllegalArgumentException.class, () -> badService.store("k", secret));
+ }
+
// -----------------------------------------------------------------------------------------------------------------
// Backend failures (non-zero, non-"not found" exit) via a scripted runner.
// -----------------------------------------------------------------------------------------------------------------
@@ -361,6 +427,31 @@ class KeychainSecretStore_Test {
}
}
+ // -----------------------------------------------------------------------------------------------------------------
+ // Real login keychain (opt-in; macOS only).
+ // -----------------------------------------------------------------------------------------------------------------
+
+ @Test void f01_realKeychainRoundTrip() {
+ assumeTrue("true".equals(System.getProperty("juneau.keychain.integration")), "Set -Djuneau.keychain.integration=true to run against the real login keychain");
+ assumeTrue(System.getProperty("os.name", "").toLowerCase().contains("mac"), "macOS only");
+ assumeTrue(new File("/usr/bin/security").canExecute(), "/usr/bin/security not available");
+ var service = "org.apache.juneau.test.j0837." + UUID.randomUUID();
+ var store = new KeychainSecretStore(service, FailMode.FAIL_CLOSED, 20L);
+ var acct = "it acct \"q\" \\";
+ var secret = "pa ss\"w\\rd 'x' $y";
+ try {
+ assertFalse(store.exists(acct));
+ store.store(acct, secret.toCharArray());
+ assertTrue(store.exists(acct));
+ assertArrayEquals(secret.toCharArray(), store.find(acct).orElseThrow());
+ store.store(acct, "second".toCharArray());
+ assertArrayEquals("second".toCharArray(), store.find(acct).orElseThrow());
+ } finally {
+ store.delete(acct);
+ }
+ assertFalse(store.exists(acct));
+ }
+
private static void assertContains(String expected, String actual) {
assertTrue(actual != null && actual.contains(expected), () -> "Expected '" + actual + "' to contain '" + expected + "'");
}