forked from jsteenb2/mess
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hour_repository_test.go
350 lines (285 loc) · 9.58 KB
/
hour_repository_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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package adapters_test
import (
"context"
"errors"
"math/rand"
"os"
"sync"
"testing"
"time"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainer/adapters"
"cloud.google.com/go/firestore"
"github.com/ThreeDotsLabs/wild-workouts-go-ddd-example/internal/trainer/domain/hour"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRepository(t *testing.T) {
t.Parallel()
rand.Seed(time.Now().UTC().UnixNano())
repositories := createRepositories(t)
for i := range repositories {
// When you are looping over slice and later using iterated value in goroutine (here because of t.Parallel()),
// you need to always create variable scoped in loop body!
// More info here: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
r := repositories[i]
t.Run(r.Name, func(t *testing.T) {
// It's always a good idea to build all non-unit tests to be able to work in parallel.
// Thanks to that, your tests will be always fast and you will not be afraid to add more tests because of slowdown.
t.Parallel()
t.Run("testUpdateHour", func(t *testing.T) {
t.Parallel()
testUpdateHour(t, r.Repository)
})
t.Run("testUpdateHour_parallel", func(t *testing.T) {
t.Parallel()
testUpdateHour_parallel(t, r.Repository)
})
t.Run("testHourRepository_update_existing", func(t *testing.T) {
t.Parallel()
testHourRepository_update_existing(t, r.Repository)
})
t.Run("testUpdateHour_rollback", func(t *testing.T) {
t.Parallel()
testUpdateHour_rollback(t, r.Repository)
})
})
}
}
type Repository struct {
Name string
Repository hour.Repository
}
func createRepositories(t *testing.T) []Repository {
return []Repository{
{
Name: "Firebase",
Repository: newFirebaseRepository(t, context.Background()),
},
{
Name: "MySQL",
Repository: newMySQLRepository(t),
},
{
Name: "memory",
Repository: adapters.NewMemoryHourRepository(testHourFactory),
},
}
}
func testUpdateHour(t *testing.T, repository hour.Repository) {
t.Helper()
ctx := context.Background()
testCases := []struct {
Name string
CreateHour func(*testing.T) *hour.Hour
}{
{
Name: "available_hour",
CreateHour: func(t *testing.T) *hour.Hour {
return newValidAvailableHour(t)
},
},
{
Name: "not_available_hour",
CreateHour: func(t *testing.T) *hour.Hour {
h := newValidAvailableHour(t)
require.NoError(t, h.MakeNotAvailable())
return h
},
},
{
Name: "hour_with_training",
CreateHour: func(t *testing.T) *hour.Hour {
h := newValidAvailableHour(t)
require.NoError(t, h.ScheduleTraining())
return h
},
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.Name, func(t *testing.T) {
t.Parallel()
newHour := tc.CreateHour(t)
err := repository.UpdateHour(ctx, newHour.Time(), func(_ *hour.Hour) (*hour.Hour, error) {
// UpdateHour provides us existing/new *hour.Hour,
// but we are ignoring this hour and persisting result of `CreateHour`
// we can assert this hour later in assertHourInRepository
return newHour, nil
})
require.NoError(t, err)
assertHourInRepository(ctx, t, repository, newHour)
})
}
}
func testUpdateHour_parallel(t *testing.T, repository hour.Repository) {
if _, ok := repository.(*adapters.FirestoreHourRepository); ok {
// todo - enable after fix of https://github.com/googleapis/google-cloud-go/issues/2604
t.Skip("because of emulator bug, it's not working in Firebase")
}
t.Helper()
ctx := context.Background()
hourTime := newValidHourTime()
// we are adding available hour
err := repository.UpdateHour(ctx, hourTime, func(h *hour.Hour) (*hour.Hour, error) {
if err := h.MakeAvailable(); err != nil {
return nil, err
}
return h, nil
})
require.NoError(t, err)
workersCount := 20
workersDone := sync.WaitGroup{}
workersDone.Add(workersCount)
// closing startWorkers will unblock all workers at once,
// thanks to that it will be more likely to have race condition
startWorkers := make(chan struct{})
// if training was successfully scheduled, number of the worker is sent to this channel
trainingsScheduled := make(chan int, workersCount)
// we are trying to do race condition, in practice only one worker should be able to finish transaction
for worker := 0; worker < workersCount; worker++ {
workerNum := worker
go func() {
defer workersDone.Done()
<-startWorkers
schedulingTraining := false
err := repository.UpdateHour(ctx, hourTime, func(h *hour.Hour) (*hour.Hour, error) {
// training is already scheduled, nothing to do there
if h.HasTrainingScheduled() {
return h, nil
}
// training is not scheduled yet, so let's try to do that
if err := h.ScheduleTraining(); err != nil {
return nil, err
}
schedulingTraining = true
return h, nil
})
if schedulingTraining && err == nil {
// training is only scheduled if UpdateHour didn't return an error
trainingsScheduled <- workerNum
}
}()
}
close(startWorkers)
// we are waiting, when all workers did the job
workersDone.Wait()
close(trainingsScheduled)
var workersScheduledTraining []int
for workerNum := range trainingsScheduled {
workersScheduledTraining = append(workersScheduledTraining, workerNum)
}
assert.Len(t, workersScheduledTraining, 1, "only one worker should schedule training")
}
func testUpdateHour_rollback(t *testing.T, repository hour.Repository) {
t.Helper()
ctx := context.Background()
hourTime := newValidHourTime()
err := repository.UpdateHour(ctx, hourTime, func(h *hour.Hour) (*hour.Hour, error) {
require.NoError(t, h.MakeAvailable())
return h, nil
})
require.NoError(t, err)
err = repository.UpdateHour(ctx, hourTime, func(h *hour.Hour) (*hour.Hour, error) {
assert.True(t, h.IsAvailable())
require.NoError(t, h.MakeNotAvailable())
return h, errors.New("something went wrong")
})
require.Error(t, err)
persistedHour, err := repository.GetHour(ctx, hourTime)
require.NoError(t, err)
assert.True(t, persistedHour.IsAvailable(), "availability change was persisted, not rolled back")
}
// testHourRepository_update_existing is testing path of creating a new hour and updating this hour.
func testHourRepository_update_existing(t *testing.T, repository hour.Repository) {
t.Helper()
ctx := context.Background()
testHour := newValidAvailableHour(t)
err := repository.UpdateHour(ctx, testHour.Time(), func(_ *hour.Hour) (*hour.Hour, error) {
return testHour, nil
})
require.NoError(t, err)
assertHourInRepository(ctx, t, repository, testHour)
var expectedHour *hour.Hour
err = repository.UpdateHour(ctx, testHour.Time(), func(h *hour.Hour) (*hour.Hour, error) {
if err := h.ScheduleTraining(); err != nil {
return nil, err
}
expectedHour = h
return h, nil
})
require.NoError(t, err)
assertHourInRepository(ctx, t, repository, expectedHour)
}
func TestNewDateDTO(t *testing.T) {
t.Parallel()
testCases := []struct {
Time time.Time
ExpectedDateTime time.Time
}{
{
Time: time.Date(3333, 1, 1, 0, 0, 0, 0, time.UTC),
ExpectedDateTime: time.Date(3333, 1, 1, 0, 0, 0, 0, time.UTC),
},
{
// we are storing date in UTC
// it's still 1 January 22:00 in UTC while it's midnight in +2 timezone
Time: time.Date(3333, 1, 2, 0, 0, 0, 0, time.FixedZone("FOO", 2*60*60)),
ExpectedDateTime: time.Date(3333, 1, 1, 0, 0, 0, 0, time.UTC),
},
}
for _, c := range testCases {
c := c
t.Run(c.Time.String(), func(t *testing.T) {
t.Parallel()
dateDTO := adapters.NewEmptyDateDTO(c.Time)
assert.True(t, dateDTO.Date.Equal(c.ExpectedDateTime), "%s != %s", dateDTO.Date, c.ExpectedDateTime)
})
}
}
// in general global state is not the best idea, but sometimes rules have some exceptions!
// in tests it's just simpler to re-use one instance of the factory
var testHourFactory = hour.MustNewFactory(hour.FactoryConfig{
// 500 weeks gives us enough entropy to avoid duplicated dates
// (even if duplicate dates should be not a problem)
MaxWeeksInTheFutureToSet: 500,
MinUtcHour: 0,
MaxUtcHour: 24,
})
func newFirebaseRepository(t *testing.T, ctx context.Context) *adapters.FirestoreHourRepository {
firestoreClient, err := firestore.NewClient(ctx, os.Getenv("GCP_PROJECT"))
require.NoError(t, err)
return adapters.NewFirestoreHourRepository(firestoreClient, testHourFactory)
}
func newMySQLRepository(t *testing.T) *adapters.MySQLHourRepository {
db, err := adapters.NewMySQLConnection()
require.NoError(t, err)
return adapters.NewMySQLHourRepository(db, testHourFactory)
}
func newValidAvailableHour(t *testing.T) *hour.Hour {
hourTime := newValidHourTime()
hour, err := testHourFactory.NewAvailableHour(hourTime)
require.NoError(t, err)
return hour
}
// usedHours is storing hours used during the test,
// to ensure that within one test run we are not using the same hour
// (it should be not a problem between test runs)
var usedHours = sync.Map{}
func newValidHourTime() time.Time {
for {
minTime := time.Now().AddDate(0, 0, 1)
minTimestamp := minTime.Unix()
maxTimestamp := minTime.AddDate(0, 0, testHourFactory.Config().MaxWeeksInTheFutureToSet*7).Unix()
t := time.Unix(rand.Int63n(maxTimestamp-minTimestamp)+minTimestamp, 0).Truncate(time.Hour).Local()
_, alreadyUsed := usedHours.LoadOrStore(t.Unix(), true)
if !alreadyUsed {
return t
}
}
}
func assertHourInRepository(ctx context.Context, t *testing.T, repo hour.Repository, hour *hour.Hour) {
require.NotNil(t, hour)
hourFromRepo, err := repo.GetHour(ctx, hour.Time())
require.NoError(t, err)
assert.Equal(t, hour, hourFromRepo)
}