go.temporal.io/server@v1.23.0/common/clock/context_test.go (about) 1 // The MIT License 2 // 3 // Copyright (c) 2020 Temporal Technologies Inc. All rights reserved. 4 // 5 // Copyright (c) 2020 Uber Technologies, Inc. 6 // 7 // Permission is hereby granted, free of charge, to any person obtaining a copy 8 // of this software and associated documentation files (the "Software"), to deal 9 // in the Software without restriction, including without limitation the rights 10 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 // copies of the Software, and to permit persons to whom the Software is 12 // furnished to do so, subject to the following conditions: 13 // 14 // The above copyright notice and this permission notice shall be included in 15 // all copies or substantial portions of the Software. 16 // 17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 // THE SOFTWARE. 24 25 package clock_test 26 27 import ( 28 "context" 29 "testing" 30 "time" 31 32 "github.com/stretchr/testify/assert" 33 "go.temporal.io/server/common/clock" 34 ) 35 36 func TestContextWithTimeout_Canceled(t *testing.T) { 37 t.Parallel() 38 39 timeSource := clock.NewEventTimeSource() 40 timeSource.Update(time.Unix(0, 0)) 41 ctx := context.Background() 42 ctx, cancel := clock.ContextWithTimeout(ctx, time.Second, timeSource) 43 deadline, ok := ctx.Deadline() 44 assert.True(t, ok) 45 assert.Equal(t, time.Unix(1, 0), deadline) 46 cancel() 47 select { 48 case <-ctx.Done(): 49 assert.ErrorIs(t, ctx.Err(), context.Canceled) 50 default: 51 t.Fatal("expected context to be canceled") 52 } 53 } 54 55 func TestContextWithTimeout_Fire(t *testing.T) { 56 t.Parallel() 57 58 timeSource := clock.NewEventTimeSource() 59 timeSource.Update(time.Unix(0, 0)) 60 ctx := context.Background() 61 ctx, cancel := clock.ContextWithTimeout(ctx, time.Second, timeSource) 62 deadline, ok := ctx.Deadline() 63 assert.True(t, ok) 64 assert.Equal(t, time.Unix(1, 0), deadline) 65 timeSource.Advance(time.Second - time.Millisecond) 66 select { 67 case <-ctx.Done(): 68 t.Fatal("expected context to not be canceled") 69 default: 70 assert.NoError(t, ctx.Err()) 71 } 72 timeSource.Advance(time.Millisecond) 73 select { 74 case <-ctx.Done(): 75 assert.ErrorIs(t, ctx.Err(), context.DeadlineExceeded) 76 default: 77 t.Fatal("expected context to be canceled") 78 } 79 cancel() // should be a no-op 80 }