github.com/letsencrypt/trillian@v1.1.2-0.20180615153820-ae375a99d36a/util/time_test.go (about) 1 // Copyright 2018 Google Inc. All Rights Reserved. 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 util 16 17 import ( 18 "context" 19 "fmt" 20 "testing" 21 "time" 22 ) 23 24 var ( 25 cases = []struct { 26 dur time.Duration 27 timeout time.Duration 28 cancel bool 29 wantErr error 30 }{ 31 {dur: 0 * time.Second, timeout: time.Second}, 32 {dur: 10 * time.Millisecond, timeout: 20 * time.Millisecond}, 33 {dur: 20 * time.Millisecond, timeout: 10 * time.Millisecond, wantErr: context.DeadlineExceeded}, 34 {dur: 1 * time.Millisecond, timeout: 0 * time.Second, wantErr: context.DeadlineExceeded}, 35 {dur: 10 * time.Millisecond, timeout: 20 * time.Millisecond, cancel: true, wantErr: context.Canceled}, 36 } 37 ) 38 39 func TestSleep(t *testing.T) { 40 for _, tc := range cases { 41 t.Run(fmt.Sprintf("%v:%v", tc.dur, tc.timeout), func(t *testing.T) { 42 ctx, cancel := context.WithTimeout(context.Background(), tc.timeout) 43 if tc.cancel { 44 cancel() 45 } else { 46 defer cancel() 47 } 48 if got, want := Sleep(ctx.Done(), tc.dur), (tc.wantErr == nil); got != want { 49 t.Errorf("Sleep() returned %v, want %v", got, want) 50 } 51 }) 52 } 53 } 54 55 func TestSleepContext(t *testing.T) { 56 for _, tc := range cases { 57 t.Run(fmt.Sprintf("%v:%v", tc.dur, tc.timeout), func(t *testing.T) { 58 ctx, cancel := context.WithTimeout(context.Background(), tc.timeout) 59 if tc.cancel { 60 cancel() 61 } else { 62 defer cancel() 63 } 64 if got, want := SleepContext(ctx, tc.dur), tc.wantErr; got != want { 65 t.Errorf("SleepContext() returned %v, want %v", got, want) 66 } 67 }) 68 } 69 }