File: testutil.go

package info (click to toggle)
golang-github-araddon-gou 0.0~git20180509.7db4be5-1.1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 160 kB
  • sloc: makefile: 2
file content (74 lines) | stat: -rw-r--r-- 1,427 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package gou

import (
	"os"
	"time"
)

var (
	//finished chan bool
	lastTest time.Time = time.Now()
	stopper  func()    = func() {}
)

// Wait for condition (defined by func) to be true
// this is mostly for testing, but a utility to
// create a ticker checking back every 100 ms to see
// if something (the supplied check func) is done
//
//   WaitFor(func() bool {
//      return ctr.Ct == 0
//   },10)
// timeout (in seconds) is the last arg
func WaitFor(check func() bool, timeoutSecs int) {
	timer := time.NewTicker(100 * time.Millisecond)
	for {
		select {
		case <-timer.C:
			if check() {
				timer.Stop()
				return
			}
		case <-time.After(time.Duration(timeoutSecs) * time.Second):
			return
		}
	}
}

// Use this in combo with StopCheck() for test functions that must start
// processes such as
func SetStopper(f func()) {
	stopper = f
}

// take two floats, compare, need to be within 2%
func CloseEnuf(a, b float64) bool {
	c := a / b
	if c > .98 && c < 1.02 {
		return true
	}
	return false
}

// take two ints, compare, need to be within 5%
func CloseInt(a, b int) bool {
	c := float64(a) / float64(b)
	if c >= .95 && c <= 1.05 {
		return true
	}
	return false
}

func StartTest() {
	lastTest = time.Now()
}

func StopCheck() {
	t := time.Now()
	if lastTest.Add(time.Millisecond*1000).UnixNano() < t.UnixNano() {
		Log(INFO, "Stopping Test ", lastTest.Unix())
		//finished <- true
		stopper()
		os.Exit(0)
	}
}