This repository has been archived by the owner on Sep 29, 2020. It is now read-only.
generated from OtusGolang/home_work
-
Notifications
You must be signed in to change notification settings - Fork 2
/
run_test.go
101 lines (78 loc) · 2.38 KB
/
run_test.go
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package hw05_parallel_execution //nolint:golint,stylecheck
import (
"fmt"
"math/rand"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
)
func TestRun(t *testing.T) {
defer goleak.VerifyNone(t)
t.Run("if were errors in first M tasks, than finished not more N+M tasks", func(t *testing.T) {
tasksCount := 50
tasks := make([]Task, 0, tasksCount)
var runTasksCount int32
for i := 0; i < tasksCount; i++ {
err := fmt.Errorf("error from task %d", i)
tasks = append(tasks, func() error {
time.Sleep(time.Millisecond * time.Duration(rand.Intn(100)))
atomic.AddInt32(&runTasksCount, 1)
return err
})
}
workersCount := 10
maxErrorsCount := 23
result := Run(tasks, workersCount, maxErrorsCount)
require.Equal(t, ErrErrorsLimitExceeded, result)
require.LessOrEqual(t, runTasksCount, int32(workersCount+maxErrorsCount), "extra tasks were started")
})
t.Run("tasks without errors", func(t *testing.T) {
tasksCount := 50
tasks := make([]Task, 0, tasksCount)
var runTasksCount int32
var sumTime time.Duration
for i := 0; i < tasksCount; i++ {
taskSleep := time.Millisecond * time.Duration(rand.Intn(100))
sumTime += taskSleep
tasks = append(tasks, func() error {
time.Sleep(taskSleep)
atomic.AddInt32(&runTasksCount, 1)
return nil
})
}
workersCount := 5
maxErrorsCount := 1
start := time.Now()
result := Run(tasks, workersCount, maxErrorsCount)
elapsedTime := time.Since(start)
require.Nil(t, result)
require.Equal(t, runTasksCount, int32(tasksCount), "not all tasks were completed")
require.LessOrEqual(t, int64(elapsedTime), int64(sumTime/2), "tasks were run sequentially?")
})
t.Run("zero error limit", func(t *testing.T) {
tasks := make([]Task, 0, 1)
tasks = append(tasks, func() error {
time.Sleep(time.Millisecond)
return nil
})
result := Run(tasks, 2, 0)
require.Equal(t, ErrErrorsLimitExceeded, result)
})
t.Run("zero task count", func(t *testing.T) {
tasks := make([]Task, 0)
result := Run(tasks, 1, 1)
require.Nil(t, result)
})
t.Run("wrong goroutines count", func(t *testing.T) {
tasks := make([]Task, 0)
result := Run(tasks, 0, 1)
require.Equal(t, ErrWrongArgument, result)
})
t.Run("wrong error limit", func(t *testing.T) {
tasks := make([]Task, 0)
result := Run(tasks, 1, -1)
require.Equal(t, ErrWrongArgument, result)
})
}