| 1 |
/* |
| 2 |
Copyright The ORAS Authors. |
| 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 |
|
| 7 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
|
| 9 |
Unless required by applicable law or agreed to in writing, software |
| 10 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
See the License for the specific language governing permissions and |
| 13 |
limitations under the License. |
| 14 |
*/ |
| 15 |
|
| 16 |
package syncutil |
| 17 |
|
| 18 |
import ( |
| 19 |
"context" |
| 20 |
"testing" |
| 21 |
|
| 22 |
"golang.org/x/sync/errgroup" |
| 23 |
) |
| 24 |
|
| 25 |
func TestMerge(t *testing.T) { |
| 26 |
var merge Merge[int] |
| 27 |
|
| 28 |
// generate expected result |
| 29 |
size := 100 |
| 30 |
factor := -1 |
| 31 |
var expected int |
| 32 |
for i := 1; i < size; i++ { |
| 33 |
expected += i * factor |
| 34 |
} |
| 35 |
|
| 36 |
// test merge |
| 37 |
ctx := context.Background() |
| 38 |
eg, _ := errgroup.WithContext(ctx) |
| 39 |
var result int |
| 40 |
for i := 1; i < size; i++ { |
| 41 |
eg.Go(func(num int) func() error { |
| 42 |
return func() error { |
| 43 |
var f int |
| 44 |
getFactor := func() error { |
| 45 |
f = factor |
| 46 |
return nil |
| 47 |
} |
| 48 |
calculate := func(items []int) error { |
| 49 |
for _, item := range items { |
| 50 |
result += item * f |
| 51 |
} |
| 52 |
return nil |
| 53 |
} |
| 54 |
return merge.Do(num, getFactor, calculate) |
| 55 |
} |
| 56 |
}(i)) |
| 57 |
} |
| 58 |
if err := eg.Wait(); err != nil { |
| 59 |
t.Errorf("Merge.Do() error = %v, wantErr %v", err, nil) |
| 60 |
} |
| 61 |
if result != expected { |
| 62 |
t.Errorf("Merge.Do() = %v, want %v", result, expected) |
| 63 |
} |
| 64 |
} |