Coverage for backend/django/core/auxiliary/formula_units.py: 75%
12 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-06-23 21:51 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2026-06-23 21:51 +0000
1from __future__ import annotations
3import re
6_UNIT_TOKEN_ALIASES = {
7 # ``min`` is a supported formula function, so bare minute units need the
8 # unambiguous Pint spelling before the expression reaches the solver.
9 "min": "minute",
10}
11_UNIT_TOKEN_PATTERN = re.compile(
12 r"\b(" + "|".join(re.escape(token) for token in _UNIT_TOKEN_ALIASES) + r")\b"
13)
16def formula_unit_expression(unit: str) -> str | None:
17 """Render a project unit string in the syntax accepted by formula expressions."""
19 cleaned = unit.strip()
20 if not cleaned: 20 ↛ 21line 20 didn't jump to line 21 because the condition on line 20 was never true
21 return ""
22 if not all(char.isalnum() or char in {"_", "/", "*", "^", ".", " "} for char in cleaned): 22 ↛ 23line 22 didn't jump to line 23 because the condition on line 22 was never true
23 return None
24 expression = cleaned.replace("^", "**").replace("/", " / ")
25 return _UNIT_TOKEN_PATTERN.sub(lambda match: _UNIT_TOKEN_ALIASES[match.group(0)], expression)