From b0badc9658e5540a67e722865b130d8cbd145abf Mon Sep 17 00:00:00 2001 From: Miro Date: Mon, 25 May 2026 20:18:50 +0200 Subject: [PATCH] Disable progress bars for non-interactive sessions --- src/diffenator2/shape.py | 10 ++++++++-- tests/test_shape.py | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 tests/test_shape.py diff --git a/src/diffenator2/shape.py b/src/diffenator2/shape.py index d5825a1..ec51ae4 100644 --- a/src/diffenator2/shape.py +++ b/src/diffenator2/shape.py @@ -5,6 +5,7 @@ from dataclasses import dataclass import uharfbuzz as hb import os +import sys from diffenator2 import THRESHOLD from diffenator2.renderer import FONT_SIZE, PixelDiffer from diffenator2.template_elements import Word, WordDiff, Glyph, GlyphDiff @@ -15,6 +16,11 @@ import csv +def _progress_bar(iterable, **kwargs): + kwargs.setdefault("disable", not getattr(sys.stderr, "isatty", lambda: False)()) + return tqdm.tqdm(iterable, **kwargs) + + # Hashing strategies for elements of a Harfbuzz buffer @@ -68,7 +74,7 @@ def test_font_glyphs(font_a, font_b, threshold=THRESHOLD, font_size=FONT_SIZE): skip_glyphs = missing_glyphs | new_glyphs modified_glyphs = [] differ = PixelDiffer(font_a, font_b, font_size=font_size) - for g in tqdm.tqdm(same_glyphs): + for g in _progress_bar(same_glyphs): pc, diff_map = differ.diff(g) if pc > threshold: glyph = GlyphDiff(g, "%.2f" % pc, diff_map) @@ -161,7 +167,7 @@ def test_words( differ = PixelDiffer(font_a, font_b, font_size=font_size) word_list = parse_wordlist(word_file) - for i, word in tqdm.tqdm(enumerate(word_list), total=len(word_list)): + for i, word in _progress_bar(enumerate(word_list), total=len(word_list)): differ.set_script(word.script) differ.set_lang(word.lang) differ.set_features(word.ot_features) diff --git a/tests/test_shape.py b/tests/test_shape.py new file mode 100644 index 0000000..30f36be --- /dev/null +++ b/tests/test_shape.py @@ -0,0 +1,38 @@ +from diffenator2 import shape + + +class _Stderr: + def __init__(self, is_tty): + self._is_tty = is_tty + + def isatty(self): + return self._is_tty + + +def test_progress_bar_is_disabled_for_non_interactive_stderr(monkeypatch): + calls = {} + + def fake_tqdm(iterable, **kwargs): + calls.update(kwargs) + return iterable + + monkeypatch.setattr(shape.sys, "stderr", _Stderr(False)) + monkeypatch.setattr(shape.tqdm, "tqdm", fake_tqdm) + + assert list(shape._progress_bar([1, 2], total=2)) == [1, 2] + assert calls["disable"] is True + assert calls["total"] == 2 + + +def test_progress_bar_is_kept_for_interactive_stderr(monkeypatch): + calls = {} + + def fake_tqdm(iterable, **kwargs): + calls.update(kwargs) + return iterable + + monkeypatch.setattr(shape.sys, "stderr", _Stderr(True)) + monkeypatch.setattr(shape.tqdm, "tqdm", fake_tqdm) + + assert list(shape._progress_bar([1, 2])) == [1, 2] + assert calls["disable"] is False