github.com/aquayi/gokit@v0.0.0-20170805152833-88827a405d9b/time_test.go (about) 1 package GoKit 2 3 import ( 4 "fmt" 5 "testing" 6 "time" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func Test_DateOf(t *testing.T) { 12 timestamp := 1136185384 + 28800 // "2006-01-02 15:03:04 +0000 UTC" 13 tm := time.Now() 14 zone, offset := tm.Zone() 15 expected := fmt.Sprintf("2006-01-02 15:03:04 +%02d00 %s", offset/3600, zone) 16 assert.Equal(t, expected, DateOf(int64(timestamp-offset))) 17 } 18 19 func wrongDuration(beginTime time.Time, Duration, checkCycle time.Duration) bool { 20 return time.Since(beginTime) < Duration || 21 Duration+checkCycle < time.Since(beginTime) 22 } 23 24 func Test_WaitFunc(t *testing.T) { 25 beginTime := time.Now() 26 checkCycle := time.Millisecond * 100 27 28 waitCh, wait := WaitFunc(checkCycle, "Test_WaitFunc") 29 30 wait() 31 t.Log(time.Now()) 32 waitDuration := checkCycle 33 if wrongDuration(beginTime, waitDuration, checkCycle) { 34 t.Error("wait()在最小时间前结束了。") 35 } 36 37 updateCycle2 := time.Millisecond * 500 38 waitCh <- updateCycle2 39 wait() 40 t.Log(time.Now()) 41 waitDuration += updateCycle2 42 if wrongDuration(beginTime, waitDuration, checkCycle) { 43 t.Error("wait()没能在updateCycle结束前,修改为更大的updateCycle") 44 } 45 46 updateCycle3 := time.Millisecond * 200 47 go func() { 48 time.Sleep(updateCycle3 / 2) 49 waitCh <- updateCycle3 50 }() 51 wait() 52 t.Log(time.Now()) 53 waitDuration += updateCycle3 54 if wrongDuration(beginTime, waitDuration, checkCycle) { 55 t.Error("wait()没能在updateCycle结束前,修改为更小的updateCycle") 56 } 57 58 waitCh <- checkCycle / 2 59 wait() 60 } 61 func Test_SleepFunc(t *testing.T) { 62 beginTime := time.Now() 63 waitDuration := 100 * time.Millisecond 64 deltaDuration := 3 * time.Millisecond 65 66 sleep := SleepFunc(waitDuration) 67 sleep() 68 t.Logf("sleep() 预计休眠%s, 实际休眠%s", waitDuration, time.Since(beginTime)) 69 assert.True(t, !wrongDuration(beginTime, waitDuration, deltaDuration), 70 "sleep() 没有休眠正确的时间:%s", waitDuration) 71 } 72 73 func Test_ParseLocalTime(t *testing.T) { 74 now := time.Now() 75 timeStr := now.Format("2006-01-02 15:04:05") 76 plt, err := ParseLocalTime(timeStr) 77 78 assert.Nil(t, err, "转换失败: %s", err) 79 assert.Zero(t, now.Unix()-plt.Unix(), "无法把%s转换成%s,而是转换成了%s", timeStr, now, plt) 80 81 wrongFormat := "2006/01/02 15:04:05" 82 wrongTime, err := ParseLocalTime(wrongFormat) 83 assert.NotNil(t, err, "把错误的格式的时间%s,转换成了%s", wrongFormat, wrongTime) 84 }