Skip to content

Commit 72d7ffa

Browse files
Fix duration formatting
Still issues with tests using below-microsecond nanosecond values, but these tests use millisecond values, so we can fix them up.
1 parent a2fe978 commit 72d7ffa

File tree

2 files changed

+8
-7
lines changed

2 files changed

+8
-7
lines changed

protovalidate/internal/string_format.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import celpy # type: ignore
1616
from celpy import celtypes # type: ignore
17+
from decimal import Decimal
1718

1819
QUOTE_TRANS = str.maketrans(
1920
{
@@ -154,6 +155,8 @@ def format_string(self, arg: celtypes.Value) -> celpy.Result:
154155
return celtypes.StringType(str(arg).lower())
155156
if isinstance(arg, celtypes.DoubleType):
156157
return celtypes.StringType(f"{arg:.0f}")
158+
if isinstance(arg, celtypes.DurationType):
159+
return celtypes.StringType(self._format_duration(arg))
157160
if isinstance(arg, celtypes.TimestampType):
158161
base = arg.isoformat()
159162
if arg.getMilliseconds() != 0:
@@ -167,7 +170,7 @@ def format_value(self, arg: celtypes.Value) -> celpy.Result:
167170
if isinstance(arg, celtypes.UintType):
168171
return celtypes.StringType(arg)
169172
if isinstance(arg, celtypes.DurationType):
170-
return celtypes.StringType(f'duration("{arg.seconds + (arg.microseconds // 1e6):.0f}s")')
173+
return celtypes.StringType(f'duration("{self._format_duration(arg)}")')
171174
if isinstance(arg, celtypes.DoubleType):
172175
return celtypes.StringType(f"{arg:f}")
173176
return self.format_string(arg)
@@ -181,6 +184,9 @@ def format_list(self, arg: celtypes.ListType) -> celpy.Result:
181184
result += "]"
182185
return celtypes.StringType(result)
183186

187+
def _format_duration(self, arg: celtypes.DurationType) -> celpy.Result:
188+
return f"{arg.seconds + Decimal(arg.microseconds) / Decimal(1_000_000):f}s"
189+
184190

185191
_default_format = StringFormat("en_US")
186192
format = _default_format.format # noqa: A001

tests/conformance/nonconforming.yaml

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,7 @@
33
standard_constraints/well_known_types/duration:
44
- gte_lte/invalid/above
55
- lte/invalid
6-
- gte/invalid
7-
- gt/invalid
8-
- in/invalid
9-
- "not in/valid"
6+
- not in/valid
107
standard_constraints/well_known_types/timestamp:
118
- gte_lte/invalid/above
129
- lte/invalid
13-
standard_constraints/repeated:
14-
- duration/gte/invalid

0 commit comments

Comments
 (0)