Debian Codegraph @

common/para/para_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 c := qt.New(t)
33
34 c.Run("Order", func(c *qt.C) {
35 if runtime.NumCPU() < 4 {
36 c.Skipf("skip Order subtest, CPU count is %d", runtime.NumCPU())
37 }
38 if htesting.IsCI() {
39 c.Skip("skip Order subtest when running on CI")
40 }
41
42 n := 500
43 ints := make([]int, n)
44 for i := range n {
45 ints[i] = i
46 }
47
48 p := New(4)
49 r, _ := p.Start(context.Background())
50
51 var result []int
52 var mu sync.Mutex
53 for i := range n {
54 r.Run(func() error {
55 mu.Lock()
56 defer mu.Unlock()
57 result = append(result, i)
58 return nil
59 })
60 }
61
62 c.Assert(r.Wait(), qt.IsNil)
63 c.Assert(result, qt.HasLen, len(ints))
64 c.Assert(sort.IntsAreSorted(result), qt.Equals, false, qt.Commentf("Para does not seem to be parallel"))
65 sort.Ints(result)
66 c.Assert(result, qt.DeepEquals, ints)
67 })
68
69 c.Run("Time", func(c *qt.C) {
70 synctest.Test(c.TB.(*testing.T), func(t *testing.T) {
71 c := qt.New(t)
72 const n = 100
73
74 p := New(5)
75 r, _ := p.Start(context.Background())
76
77 start := time.Now()
78
79 var counter int64
80
81 for range n {
82 r.Run(func() error {
83 atomic.AddInt64(&counter, 1)
84 time.Sleep(1 * time.Millisecond)
85 return nil
86 })
87 }
88
89 c.Assert(r.Wait(), qt.IsNil)
90 c.Assert(counter, qt.Equals, int64(n))
91
92 since := time.Since(start)
93 limit := n / 2 * time.Millisecond
94 c.Assert(since < limit, qt.Equals, true, qt.Commentf("%s >= %s", since, limit))
95 })
96 })
97 }