github.com/richardwilkes/toolbox@v1.121.0/txt/duration_test.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 package txt_test 11 12 import ( 13 "fmt" 14 "testing" 15 "time" 16 17 "github.com/richardwilkes/toolbox/check" 18 "github.com/richardwilkes/toolbox/txt" 19 ) 20 21 func TestFormatDuration(t *testing.T) { 22 for i, one := range []struct { 23 Expected string 24 Duration time.Duration 25 IncludeMillis bool 26 }{ 27 {"0:00:00.001", time.Millisecond, true}, 28 {"0:00:01.000", 1000 * time.Millisecond, true}, 29 {"0:00:01", 1001 * time.Millisecond, false}, 30 {"0:00:01", 1999 * time.Millisecond, false}, 31 {"0:01:01", 61 * time.Second, false}, 32 {"1:01:00", 61 * time.Minute, false}, 33 {"61:00:00", 61 * time.Hour, false}, 34 } { 35 check.Equal(t, one.Expected, txt.FormatDuration(one.Duration, one.IncludeMillis), "Index %d", i) 36 } 37 } 38 39 func TestParseDuration(t *testing.T) { 40 for i, one := range []struct { 41 Input string 42 ExpectedDuration time.Duration 43 ExpectErr bool 44 }{ 45 {"0:00:00.001", time.Millisecond, false}, 46 {"0.001", 0, true}, 47 {"0:0.001", 0, true}, 48 {"0:0:.001", 0, true}, 49 {"0:0:0.001", time.Millisecond, false}, 50 {"0:0:-1.001", 0, true}, 51 {"-1:0:0.001", 0, true}, 52 {"0:-1:0.001", 0, true}, 53 {"0:0:0.-001", 0, true}, 54 {"0:1:61.001", 2*time.Minute + time.Second + time.Millisecond, false}, 55 } { 56 result, err := txt.ParseDuration(one.Input) 57 desc := fmt.Sprintf("Index %d: %s", i, one.Input) 58 if one.ExpectErr { 59 check.Error(t, err, desc) 60 } else { 61 check.NoError(t, err, desc) 62 check.Equal(t, one.ExpectedDuration, result, desc) 63 } 64 } 65 }