github.com/ericwq/aprilsh@v0.0.0-20240517091432-958bc568daa0/frontend/client/timer_test.go (about) 1 // Copyright 2022~2023 wangqi. All rights reserved. 2 // Use of this source code is governed by a MIT-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "testing" 9 "time" 10 ) 11 12 func TestTimer(t *testing.T) { 13 tc := []struct { 14 label string 15 timeout int 16 expect int64 17 }{ 18 {"positive timer", 5, 5}, 19 {"zero timer", 0, 0}, 20 {"negative timer", -2000, 0}, // negative value means triger timer immediately 21 } 22 23 for _, v := range tc { 24 t.Run(v.label, func(t *testing.T) { 25 now := time.Now().UnixMilli() 26 timer := time.NewTimer(time.Duration(v.timeout) * time.Millisecond) 27 28 <-timer.C 29 30 got := time.Now().UnixMilli() - now 31 if !(got-v.expect == 0 || got-v.expect <= 2) { // asllow 1ms deviation 32 t.Skip("#test timer failed") 33 // t.Errorf("#test %s expect %d, got %d\n", v.label, v.expect, got) 34 } 35 }) 36 } 37 }