Debian Codegraph @

scripts/_utils.py

raw
1 """Cross-platform console symbol selection for live test scripts.
2
3 Detects whether the active stdout encoding can represent a small set of
4 Unicode emoji used for nicer test status output. Falls back to plain ASCII
5 strings when running in limited code pages (e.g. Windows cp1252 on some
6 GitHub Actions runners) to avoid UnicodeEncodeError crashes.
7
8 Usage:
9 from scripts._symbols import get_symbols
10 SYMS = get_symbols()
11 print(SYMS['PASS'], 'Test passed')
12
13 Provided symbol keys:
14 PASS, FAIL, SUMMARY, TEST, PG
15
16 The ``PG`` key is only used by the PostgreSQL live test; others are shared.
17 """
18
19 from __future__ import annotations
20
21 import contextlib
22 import sys
23
24 _EMOJI_SYMBOLS = {
25 "PASS": "✅",
26 "FAIL": "❌",
27 "SUMMARY": "📊",
28 "TEST": "📋",
29 "PG": "🐘",
30 "SKIP": "⚠️",
31 }
32
33 _ASCII_SYMBOLS = {
34 "PASS": "PASS:",
35 "FAIL": "FAIL:",
36 "SUMMARY": "SUMMARY:",
37 "TEST": "TEST:",
38 "PG": ">>",
39 "SKIP": "SKIP:",
40 }
41
42
43 def _can_encode(sample: str) -> bool:
44 """Return True if current stdout encoding can represent ``sample``."""
45 encoding = getattr(sys.stdout, "encoding", None) or ""
46 if not encoding:
47 return False
48 with contextlib.suppress(Exception):
49 sample.encode(encoding)
50 return True
51 return False
52
53
54 def get_symbols() -> dict[str, str]: # - short descriptive name
55 """Return mapping of symbol names to appropriate (emoji or ASCII) strings."""
56 if all(_can_encode(sym) for sym in _EMOJI_SYMBOLS.values()):
57 return _EMOJI_SYMBOLS
58 return _ASCII_SYMBOLS
59
60
61 __all__ = ["get_symbols"]