From 0ef98ee1bdc7b205bfce8d29750a680ed5a87c89 Mon Sep 17 00:00:00 2001 From: fbirds5230 Date: Thu, 26 Nov 2026 03:40:15 +0100 Subject: [PATCH] Reject numeric components that fail to parse Return ErrUnsupportedFormat when ParseFloat rejects a duration component, instead of silently returning a zero or partial duration without an error. Cover malformed numbers in every unit and preserve existing decimal and mixed week/time inputs. --- duration.go | 2 ++ duration_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/duration.go b/duration.go index d5761a7..863e3a0 100644 --- a/duration.go +++ b/duration.go @@ -125,6 +125,8 @@ func durationFromMatchAndPrefix(match []string, prefix string) (time.Duration, e case "seconds": d += duration("%fs", f) } + } else { + return 0, ErrUnsupportedFormat } } diff --git a/duration_test.go b/duration_test.go index 44af706..abfbd7b 100644 --- a/duration_test.go +++ b/duration_test.go @@ -111,3 +111,34 @@ func ExampleParse() { // Output: 2m5s } + +func TestParseNumericComponents(t *testing.T) { + for _, tt := range []struct { + dur string + err error + out time.Duration + }{ + {"P.Y", duration.ErrUnsupportedFormat, 0}, + {"P1..5M", duration.ErrUnsupportedFormat, 0}, + {"P..W", duration.ErrUnsupportedFormat, 0}, + {"P.5.5D", duration.ErrUnsupportedFormat, 0}, + {"PT1..5H", duration.ErrUnsupportedFormat, 0}, + {"PT..M", duration.ErrUnsupportedFormat, 0}, + {"PT1..5S", duration.ErrUnsupportedFormat, 0}, + {"P1Y..M", duration.ErrUnsupportedFormat, 0}, + {"P..YT1S", duration.ErrUnsupportedFormat, 0}, + {"-P1DT1..5S", duration.ErrUnsupportedFormat, 0}, + {"PT.5S", nil, 500 * time.Millisecond}, + {"PT1.S", nil, time.Second}, + {"PT0.5H29M60S", nil, time.Hour}, + {"P1WT0.5H", nil, 168*time.Hour + 30*time.Minute}, + {"-P1WT0.5H", nil, -(168*time.Hour + 30*time.Minute)}, + } { + t.Run(tt.dur, func(t *testing.T) { + d, err := duration.Parse(tt.dur) + if d != tt.out || err != tt.err { + t.Errorf("Parse(%q) = (%v, %v), want (%v, %v)", tt.dur, d, err, tt.out, tt.err) + } + }) + } +}