|
| 1 | +// Copyright 2025 The Cockroach Authors. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| 12 | +// implied. See the License for the specific language governing |
| 13 | +// permissions and limitations under the License. |
| 14 | + |
| 15 | +package crhumanize |
| 16 | + |
| 17 | +import ( |
| 18 | + "fmt" |
| 19 | + "math/rand/v2" |
| 20 | + "strings" |
| 21 | + "testing" |
| 22 | + "time" |
| 23 | + |
| 24 | + "github.com/cockroachdb/crlib/crstrings" |
| 25 | + "github.com/cockroachdb/crlib/internal/datadriven" |
| 26 | +) |
| 27 | + |
| 28 | +func TestDuration(t *testing.T) { |
| 29 | + datadriven.RunTest(t, "testdata/duration", func(t *testing.T, td *datadriven.TestData) string { |
| 30 | + if td.Cmd != "duration" { |
| 31 | + td.Fatalf(t, "unknown command: %q", td.Cmd) |
| 32 | + } |
| 33 | + var buf strings.Builder |
| 34 | + for _, l := range crstrings.Lines(td.Input) { |
| 35 | + d, err := time.ParseDuration(l) |
| 36 | + if err != nil { |
| 37 | + td.Fatalf(t, "could not parse duration %q: %v", l, err) |
| 38 | + } |
| 39 | + fmt.Fprintf(&buf, "%s -> %s\n", d, Duration(d)) |
| 40 | + } |
| 41 | + return buf.String() |
| 42 | + }) |
| 43 | +} |
| 44 | + |
| 45 | +func TestDurationError(t *testing.T) { |
| 46 | + for _, v := range []time.Duration{time.Microsecond, time.Second, time.Minute, time.Hour, 100 * time.Hour, 10000 * time.Hour} { |
| 47 | + for i := 0; i < 1000; i++ { |
| 48 | + d := time.Duration(rand.Int64N(int64(v))) |
| 49 | + s := string(Duration(d)) |
| 50 | + d1, err := time.ParseDuration(s) |
| 51 | + if err != nil { |
| 52 | + t.Fatalf("%s: could not parse duration %q: %v", d, s, err) |
| 53 | + } |
| 54 | + if d1 < 89*d/100 || d1 > 111*d/100 { |
| 55 | + t.Fatalf("%s -> %s -> %s error is too large\n", d, s, d1) |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments