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
| package main
import ( "context" "encoding/json" "sync" "testing"
"github.com/stretchr/testify/assert" )
type Class struct { Id int64 `json:"id"` Name string `json:"name"` Grade string `json:"grade"` Student []*Student `json:"student"` }
type Student struct { Id int64 `json:"id"` ClassId int64 `json:"classId"` Name string `json:"name"` }
func TestWaitGroup(t *testing.T) { var ( mu sync.Mutex wg = sync.WaitGroup{} errs = make([]error, 0) classArr = []*Class{{Id: 1}, {Id: 2}, {Id: 3}} )
wg.Add(len(classArr)) for _, item := range classArr { go func(class *Class) { defer wg.Done() ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() students, err := queryAllStudent(ctx, class.Id) if err != nil { mu.Lock() errs = append(errs, err) mu.Unlock() return } class.Student = students }(item) } wg.Wait() assert.Equal(t, len(errs), 0)
bytes, err := json.Marshal(classArr) assert.Nil(t, err)
t.Log(string(bytes)) }
func queryAllStudent(ctx context.Context, classId int64) ([]*Student, error) { return map[int64][]*Student{ 1: []*Student{{Id: 1}, {Id: 2}, {Id: 3}}, 2: []*Student{{Id: 4}, {Id: 5}, {Id: 6}}, 3: []*Student{{Id: 7}, {Id: 8}, {Id: 9}}, }[classId], nil }
|