github.com/solo-io/cue@v0.4.7/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 TestParseDuration(t *testing.T) {
    52  	valid := []struct {
    53  		in  string
    54  		out int64
    55  		err bool
    56  	}{
    57  		{"3h2m", 3*Hour + 2*Minute, false},
    58  		{"5s", 5 * Second, false},
    59  		{"5d", 0, true},
    60  	}
    61  
    62  	for _, tc := range valid {
    63  		t.Run(tc.in, func(t *testing.T) {
    64  			i, err := ParseDuration(tc.in)
    65  			if got := err != nil; got != tc.err {
    66  				t.Fatalf("error: got %v; want %v", i, tc.out)
    67  			}
    68  			if i != tc.out {
    69  				t.Errorf("got %v; want %v", i, tc.out)
    70  			}
    71  		})
    72  	}
    73  }