github.com/gravitational/teleport/api@v0.0.0-20240507183017-3110591cbafc/types/duration_test.go (about)

     1  /*
     2  Copyright 2022 Gravitational, Inc.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package types
    18  
    19  import (
    20  	"testing"
    21  	"time"
    22  
    23  	"github.com/stretchr/testify/require"
    24  )
    25  
    26  type testCase struct {
    27  	name          string
    28  	stringValue   string
    29  	expectedValue Duration
    30  }
    31  
    32  // TestDurationUnmarshal tests unmarshaling of various duration formats.
    33  func TestDurationUnmarshal(t *testing.T) {
    34  	testCases := []testCase{
    35  		{
    36  			name:          "simple",
    37  			stringValue:   `"100h"`,
    38  			expectedValue: Duration(time.Hour * 100),
    39  		},
    40  		{
    41  			name:          "combined large",
    42  			stringValue:   `"1y6mo"`,
    43  			expectedValue: Duration(time.Hour*24*365 + time.Hour*24*30*6),
    44  		},
    45  		{
    46  			name:          "large + small",
    47  			stringValue:   `"24d30μs"`,
    48  			expectedValue: Duration(time.Hour*24*24 + time.Microsecond*30),
    49  		},
    50  	}
    51  
    52  	for _, testCase := range testCases {
    53  		t.Run(testCase.name, func(t *testing.T) {
    54  			var duration Duration
    55  			err := duration.UnmarshalJSON([]byte(testCase.stringValue))
    56  			require.NoError(t, err)
    57  			require.Equal(t, testCase.expectedValue, duration)
    58  		})
    59  	}
    60  }