cuelang.org/go@v0.10.1/pkg/time/duration_test.go (about) 1 // Copyright 2019 CUE 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 implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package time 16 17 import ( 18 "testing" 19 ) 20 21 func TestDuration(t *testing.T) { 22 valid := []string{ 23 "1.0s", 24 "1000.0s", 25 "1000.000001s", 26 ".000001s", 27 "4h2m", 28 } 29 30 for _, tc := range valid { 31 t.Run(tc, func(t *testing.T) { 32 if b, err := Duration(tc); !b || err != nil { 33 t.Errorf("CUE eval failed unexpectedly: %v", err) 34 } 35 }) 36 } 37 38 invalid := []string{ 39 "5d2h", 40 } 41 42 for _, tc := range invalid { 43 t.Run(tc, func(t *testing.T) { 44 if _, err := Duration(tc); err == nil { 45 t.Errorf("CUE eval succeeded unexpectedly") 46 } 47 }) 48 } 49 } 50 51 func TestFormatDuration(t *testing.T) { 52 valid := []struct { 53 in int64 54 out string 55 }{ 56 {3*Hour + 2*Minute, "3h2m0s"}, 57 {5 * Second, "5s"}, 58 {600 * Millisecond, "600ms"}, 59 } 60 61 for _, tc := range valid { 62 t.Run(tc.out, func(t *testing.T) { 63 s := FormatDuration(tc.in) 64 if s != tc.out { 65 t.Fatalf("got %v; want %v", s, tc.out) 66 } 67 }) 68 } 69 } 70 71 func TestParseDuration(t *testing.T) { 72 valid := []struct { 73 in string 74 out int64 75 err bool 76 }{ 77 {"3h2m", 3*Hour + 2*Minute, false}, 78 {"5s", 5 * Second, false}, 79 {"5d", 0, true}, 80 } 81 82 for _, tc := range valid { 83 t.Run(tc.in, func(t *testing.T) { 84 i, err := ParseDuration(tc.in) 85 if got := err != nil; got != tc.err { 86 t.Fatalf("error: got %v; want %v", i, tc.out) 87 } 88 if i != tc.out { 89 t.Errorf("got %v; want %v", i, tc.out) 90 } 91 }) 92 } 93 }