1package syncutil 2 3import ( 4 "errors" 5 "testing" 6) 7 8func TestOnce(t *testing.T) { 9 timesRan := 0 10 f := func() error { 11 timesRan++ 12 return nil 13 } 14 15 once := Once{} 16 grp := Group{} 17 18 for i := 0; i < 10; i++ { 19 grp.Go(func() error { return once.Do(f) }) 20 } 21 22 if grp.Err() != nil { 23 t.Errorf("Expected no errors, got %v", grp.Err()) 24 } 25 26 if timesRan != 1 { 27 t.Errorf("Expected to run one time, ran %d", timesRan) 28 } 29} 30 31// TestOnceErroring verifies we retry on every error, but stop after 32// the first success. 33func TestOnceErroring(t *testing.T) { 34 timesRan := 0 35 f := func() error { 36 timesRan++ 37 if timesRan < 3 { 38 return errors.New("retry") 39 } 40 return nil 41 } 42 43 once := Once{} 44 grp := Group{} 45 46 for i := 0; i < 10; i++ { 47 grp.Go(func() error { return once.Do(f) }) 48 } 49 50 if len(grp.Errs()) != 2 { 51 t.Errorf("Expected two errors, got %d", len(grp.Errs())) 52 } 53 54 if timesRan != 3 { 55 t.Errorf("Expected to run two times, ran %d", timesRan) 56 } 57} 58