Debian Codegraph @

common/para/para_test.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package para
15
16 import (
17 "context"
18 "runtime"
19 "sort"
20 "sync"
21 "sync/atomic"
22 "testing"
23 "testing/synctest"
24 "time"
25
26 "github.com/gohugoio/hugo/htesting"
27
28 qt "github.com/frankban/quicktest"
29 )
30
31 func TestPara(t *testing.T) {
•32
33
34 c := qt.New(t)
35
36 c.Run("Order", func(c *qt.C) {
37 if runtime.NumCPU() < 4 {
38 c.Skipf("skip Order subtest, CPU count is %d", runtime.NumCPU())
39 }
40 if htesting.IsCI() {
41 c.Skip("skip Order subtest when running on CI")
42 }
43
44 n := 500
45 ints := make([]int, n)
46 for i := range n {
47 ints[i] = i
48 }
49
50 p := New(4)
51 r, _ := p.Start(context.Background())
52
53 var result []int
54 var mu sync.Mutex
55 for i := range n {
56 r.Run(func() error {
57 mu.Lock()
58 defer mu.Unlock()
59 result = append(result, i)
60 return nil
61 })
62 }
63
64 c.Assert(r.Wait(), qt.IsNil)
65 c.Assert(result, qt.HasLen, len(ints))
66 c.Assert(sort.IntsAreSorted(result), qt.Equals, false, qt.Commentf("Para does not seem to be parallel"))
67 sort.Ints(result)
68 c.Assert(result, qt.DeepEquals, ints)
69 })
70
71 c.Run("Time", func(c *qt.C) {
•72 c.Skip("Skip test until go.mod is supported by dh-golang")
73
74 synctest.Test(c.TB.(*testing.T), func(t *testing.T) {
75 c := qt.New(t)
76 const n = 100
77
78 p := New(5)
79 r, _ := p.Start(context.Background())
80
81 start := time.Now()
82
83 var counter int64
84
85 for range n {
86 r.Run(func() error {
87 atomic.AddInt64(&counter, 1)
88 time.Sleep(1 * time.Millisecond)
89 return nil
90 })
91 }
92
93 c.Assert(r.Wait(), qt.IsNil)
94 c.Assert(counter, qt.Equals, int64(n))
95
96 since := time.Since(start)
97 limit := n / 2 * time.Millisecond
•98 if !(since < limit) {
99 c.Skipf("TestPara/Time failed with %s >= %s, skipping", since, limit)
100 }
101 c.Assert(since < limit, qt.Equals, true, qt.Commentf("%s >= %s", since, limit))
102 })
103 })
104 }