github.com/go-spring/spring-base@v1.1.3/clock/now_test.go (about) 1 /* 2 * Copyright 2012-2019 the original author or authors. 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 * https://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 clock_test 18 19 import ( 20 "context" 21 "testing" 22 "time" 23 24 "github.com/go-spring/spring-base/assert" 25 "github.com/go-spring/spring-base/clock" 26 "github.com/go-spring/spring-base/knife" 27 "github.com/go-spring/spring-base/run" 28 ) 29 30 func TestNow(t *testing.T) { 31 32 t.Run("normal_mode", func(t *testing.T) { 33 reset := run.SetMode(run.NormalModeFlag) 34 defer func() { reset() }() 35 ctx, _ := knife.New(context.Background()) 36 knife.Store(ctx, "::now::", time.Now().Add(time.Hour)) 37 assert.True(t, clock.Now(ctx).Sub(time.Now()) < time.Millisecond) 38 }) 39 40 t.Run("record_mode", func(t *testing.T) { 41 reset := run.SetMode(run.RecordModeFlag) 42 defer func() { reset() }() 43 ctx, _ := knife.New(context.Background()) 44 knife.Store(ctx, "::now::", time.Now().Add(time.Hour)) 45 assert.True(t, clock.Now(ctx).Sub(time.Now()) < time.Millisecond) 46 }) 47 48 t.Run("null_time", func(t *testing.T) { 49 ctx, _ := knife.New(context.Background()) 50 knife.Store(ctx, "::now::", time.Now().Add(time.Hour)) 51 assert.True(t, clock.Now(ctx).Sub(time.Now()) < time.Millisecond) 52 }) 53 54 t.Run("base_time", func(t *testing.T) { 55 ctx, _ := knife.New(context.Background()) 56 trueNow := time.Now() 57 58 err := clock.SetBaseTime(ctx, time.Unix(100, 0)) 59 assert.Nil(t, err) 60 61 time.Sleep(5 * time.Millisecond) 62 n := clock.Now(ctx).Sub(time.Unix(100, 0)) 63 assert.True(t, n > 5*time.Millisecond && n < 10*time.Millisecond) 64 65 clock.ResetTime(ctx) 66 assert.True(t, clock.Now(ctx).Sub(trueNow) < 20*time.Millisecond) 67 }) 68 69 t.Run("fixed_time", func(t *testing.T) { 70 ctx, _ := knife.New(context.Background()) 71 trueNow := time.Now() 72 73 err := clock.SetFixedTime(ctx, time.Unix(100, 0)) 74 assert.Nil(t, err) 75 76 now := clock.Now(ctx) 77 assert.Equal(t, now, time.Unix(100, 0)) 78 79 time.Sleep(10 * time.Millisecond) 80 assert.Equal(t, now, time.Unix(100, 0)) 81 82 clock.ResetTime(ctx) 83 assert.True(t, clock.Now(ctx).Sub(trueNow) < 20*time.Millisecond) 84 }) 85 }