Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use correct unmarshaller for json durations #10124

Merged
merged 5 commits into from
Feb 3, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion api/types/duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (d *Duration) UnmarshalJSON(data []byte) error {
*d = Duration(0)
return nil
}
out, err := time.ParseDuration(stringVar)
out, err := parseDuration(stringVar)
if err != nil {
return trace.BadParameter(err.Error())
}
Expand Down
62 changes: 62 additions & 0 deletions api/types/duration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
Copyright 2022 Gravitational, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package types

import (
"testing"
"time"
)

type testCase struct {
name string
stringValue string
expectedValue Duration
}

// TestDurationUnmarshal tests unmarshaling of various duration formats.
func TestDurationUnmarshal(t *testing.T) {
testCases := []testCase{
{
name: "simple",
stringValue: `"100h"`,
expectedValue: Duration(time.Hour * 100),
},
{
name: "combined large",
stringValue: `"1y6mo"`,
expectedValue: Duration(time.Hour*24*365 + time.Hour*24*30*6),
},
{
name: "large + small",
stringValue: `"24d30μs"`,
expectedValue: Duration(time.Hour*24*24 + time.Microsecond*30),
},
}

for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
var duration Duration
err := duration.UnmarshalJSON([]byte(testCase.stringValue))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if duration != testCase.expectedValue {
t.Fatalf("unexpected value: %v", duration)
}
})
}
}