|
| 1 | +package types |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/MontFerret/ferret/v2/pkg/runtime" |
| 9 | +) |
| 10 | + |
| 11 | +func TestToDuration(t *testing.T) { |
| 12 | + t.Parallel() |
| 13 | + |
| 14 | + tests := []struct { |
| 15 | + input runtime.Value |
| 16 | + name string |
| 17 | + expected runtime.Duration |
| 18 | + }{ |
| 19 | + { |
| 20 | + name: "duration", |
| 21 | + input: runtime.NewDuration(250 * time.Millisecond), |
| 22 | + expected: runtime.NewDuration(250 * time.Millisecond), |
| 23 | + }, |
| 24 | + { |
| 25 | + name: "literal string", |
| 26 | + input: runtime.NewString("1.5s"), |
| 27 | + expected: runtime.NewDuration(1500 * time.Millisecond), |
| 28 | + }, |
| 29 | + { |
| 30 | + name: "normalized string", |
| 31 | + input: runtime.NewString("1h30m"), |
| 32 | + expected: runtime.NewDuration(90 * time.Minute), |
| 33 | + }, |
| 34 | + } |
| 35 | + |
| 36 | + for _, tt := range tests { |
| 37 | + t.Run(tt.name, func(t *testing.T) { |
| 38 | + t.Parallel() |
| 39 | + |
| 40 | + actual, err := ToDuration(t.Context(), tt.input) |
| 41 | + if err != nil { |
| 42 | + t.Fatalf("ToDuration() error = %v", err) |
| 43 | + } |
| 44 | + |
| 45 | + duration, err := runtime.CastDuration(actual) |
| 46 | + if err != nil { |
| 47 | + t.Fatalf("ToDuration() result type = %s, want Duration", runtime.TypeOf(actual)) |
| 48 | + } |
| 49 | + |
| 50 | + if duration != tt.expected { |
| 51 | + t.Fatalf("ToDuration() = %s, want %s", duration, tt.expected) |
| 52 | + } |
| 53 | + }) |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +func TestToDurationRejectsUnsupportedType(t *testing.T) { |
| 58 | + t.Parallel() |
| 59 | + |
| 60 | + _, err := ToDuration(t.Context(), runtime.NewInt(1)) |
| 61 | + if !errors.Is(err, runtime.ErrInvalidType) { |
| 62 | + t.Fatalf("ToDuration() error = %v, want invalid type", err) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +func TestToDurationRejectsInvalidString(t *testing.T) { |
| 67 | + t.Parallel() |
| 68 | + |
| 69 | + if _, err := ToDuration(t.Context(), runtime.NewString("1fortnight")); err == nil { |
| 70 | + t.Fatal("ToDuration() accepted an invalid duration string") |
| 71 | + } |
| 72 | +} |
0 commit comments