1package gou 2 3import ( 4 "os" 5 "time" 6) 7 8var ( 9 //finished chan bool 10 lastTest time.Time = time.Now() 11 stopper func() = func() {} 12) 13 14// Wait for condition (defined by func) to be true 15// this is mostly for testing, but a utility to 16// create a ticker checking back every 100 ms to see 17// if something (the supplied check func) is done 18// 19// WaitFor(func() bool { 20// return ctr.Ct == 0 21// },10) 22// timeout (in seconds) is the last arg 23func WaitFor(check func() bool, timeoutSecs int) { 24 timer := time.NewTicker(100 * time.Millisecond) 25 for { 26 select { 27 case <-timer.C: 28 if check() { 29 timer.Stop() 30 return 31 } 32 case <-time.After(time.Duration(timeoutSecs) * time.Second): 33 return 34 } 35 } 36} 37 38// Use this in combo with StopCheck() for test functions that must start 39// processes such as 40func SetStopper(f func()) { 41 stopper = f 42} 43 44// take two floats, compare, need to be within 2% 45func CloseEnuf(a, b float64) bool { 46 c := a / b 47 if c > .98 && c < 1.02 { 48 return true 49 } 50 return false 51} 52 53// take two ints, compare, need to be within 5% 54func CloseInt(a, b int) bool { 55 c := float64(a) / float64(b) 56 if c >= .95 && c <= 1.05 { 57 return true 58 } 59 return false 60} 61 62func StartTest() { 63 lastTest = time.Now() 64} 65 66func StopCheck() { 67 t := time.Now() 68 if lastTest.Add(time.Millisecond*1000).UnixNano() < t.UnixNano() { 69 Log(INFO, "Stopping Test ", lastTest.Unix()) 70 //finished <- true 71 stopper() 72 os.Exit(0) 73 } 74} 75