File: once_test.go

package info (click to toggle)
golang-go4 0.0~git20190313.94abd69-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 760 kB
  • sloc: asm: 20; makefile: 4
file content (57 lines) | stat: -rw-r--r-- 949 bytes parent folder | download | duplicates (4)
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
package syncutil

import (
	"errors"
	"testing"
)

func TestOnce(t *testing.T) {
	timesRan := 0
	f := func() error {
		timesRan++
		return nil
	}

	once := Once{}
	grp := Group{}

	for i := 0; i < 10; i++ {
		grp.Go(func() error { return once.Do(f) })
	}

	if grp.Err() != nil {
		t.Errorf("Expected no errors, got %v", grp.Err())
	}

	if timesRan != 1 {
		t.Errorf("Expected to run one time, ran %d", timesRan)
	}
}

// TestOnceErroring verifies we retry on every error, but stop after
// the first success.
func TestOnceErroring(t *testing.T) {
	timesRan := 0
	f := func() error {
		timesRan++
		if timesRan < 3 {
			return errors.New("retry")
		}
		return nil
	}

	once := Once{}
	grp := Group{}

	for i := 0; i < 10; i++ {
		grp.Go(func() error { return once.Do(f) })
	}

	if len(grp.Errs()) != 2 {
		t.Errorf("Expected two errors, got %d", len(grp.Errs()))
	}

	if timesRan != 3 {
		t.Errorf("Expected to run two times, ran %d", timesRan)
	}
}