/
gopeat_test.go
677 lines (566 loc) · 17.4 KB
/
gopeat_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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
package gopeat
import (
"math"
"sync"
"testing"
"time"
)
type mockTsData struct {
Tim time.Time
Val int64
}
func (ts mockTsData) GetTimeStamp() time.Time {
return ts.Tim
}
type mockTsDataSource struct {
MaxRecs int64
RecCnt int64
DataInterval time.Duration
StartTime time.Time
}
func (st *mockTsDataSource) Next() (TimeStamper, bool) {
for {
st.RecCnt++
if st.RecCnt > st.MaxRecs {
return nil, false
}
trd := mockTsData{
Tim: st.StartTime,
Val: st.RecCnt,
}
st.StartTime.Add(st.DataInterval)
return trd, true
}
}
func (st *mockTsDataSource) SetStartTime(startTime time.Time) {
}
func (st *mockTsDataSource) SetEndTime(endTime time.Time) {
}
// A datasource that blocks on next, client should release Wg so next
// does not block the load data goroutine from shutting down
type mockTsBlockingDs struct {
Wg sync.WaitGroup
NextCalled bool
}
func (st *mockTsBlockingDs) Next() (TimeStamper, bool) {
st.Wg.Add(1)
st.NextCalled = true
st.Wg.Wait()
return nil, false
}
func (st *mockTsBlockingDs) SetStartTime(startTime time.Time) {
}
func (st *mockTsBlockingDs) SetEndTime(endTime time.Time) {
}
// Uses slice provided as data
type mockSliceBackedDs struct {
TimeStampers []TimeStamper
idx int
}
func (st *mockSliceBackedDs) Next() (TimeStamper, bool) {
if st.idx < len(st.TimeStampers) {
st.idx++
return st.TimeStampers[st.idx-1], true
}
return nil, false
}
func (st *mockSliceBackedDs) SetStartTime(startTime time.Time) {
}
func (st *mockSliceBackedDs) SetEndTime(endTime time.Time) {
}
func TestChangeRate(t *testing.T) {
// Create a new PlayBack at 2x rate
var mts mockTsBlockingDs
simStartTime := time.Now()
dataTime := simStartTime.Add(time.Second * 1)
pb, _ := New("test", simStartTime, dataTime, &mts, 2, nil)
pb.init()
// Set the read buffer to 2 so that every second record
// causes the playback to "run"
pb.tsDataBufSize = 2
// Callback measures time to first data playback send. Since
// the first time stamper is 1 second after playback start,
// the first callback should be at .5 seconds given the rate is 2x
callbackHit := false
pb.SendTs = func(ts TimeStamper) error {
callbackHit = true
wallDur := time.Since(pb.WallStartTime)
expDur := (ts.GetTimeStamp().Sub(simStartTime) / pb.rateDur)
timeDrift := wallDur - expDur
if math.Abs(timeDrift.Seconds()*1000) > 3 {
t.Errorf("Time = %f(ms); want less than 3(ms)", timeDrift.Seconds()*1000)
}
if ts.(mockTsData).Val != 6 {
t.Errorf("Val = %d; want 6", ts.(mockTsData).Val)
}
return nil
}
// Start controller wait til it's ready
pb.controllerStarted.Add(1)
go pb.controller()
pb.controllerStarted.Wait()
// Inject some data
pb.tsDataChan <- []TimeStamper{mockTsData{Tim: dataTime, Val: 6}}
pb.tsDataChan <- []TimeStamper{mockTsData{Tim: dataTime.Add(100 * time.Millisecond), Val: 6}}
time.Sleep(1 * time.Millisecond)
// Lower the rate to 1
pb.SetRate(1)
// Inject more data, the callback tests the timing given the rate
pb.tsDataChan <- []TimeStamper{mockTsData{Tim: dataTime.Add(300 * time.Millisecond), Val: 6}}
// Wait til data has been processed
mts.Wg.Done()
pb.termWg.Wait()
// Make sure callback was called
if !callbackHit {
t.Errorf("Provided PlayBack call was not executed")
}
}
func TestShortPause(t *testing.T) {
// Create a new PlayBack at 2x rate
var mts mockTsBlockingDs
simStartTime := time.Now()
dataTime := simStartTime.Add(time.Second * 1)
pb, _ := New("test", simStartTime, dataTime, &mts, 2, nil)
pb.init()
// Callback measures time to first data playback send. Since
// the first time stamper is 1 second after playback start,
// the first callback should be at .5 seconds given the rate is 2x
callbackHit := false
pb.SendTs = func(ts TimeStamper) error {
callbackHit = true
wallDur := time.Since(pb.WallStartTime)
expDur := (dataTime.Sub(simStartTime) / 2) + (time.Millisecond * 100)
timeDrift := wallDur - expDur
if math.Abs(timeDrift.Seconds()*1000) > 3 {
t.Errorf("Time = %f(ms); want less than 3(ms)", timeDrift.Seconds()*1000)
}
if ts.(mockTsData).Val != 6 {
t.Errorf("Val = %d; want 6", ts.(mockTsData).Val)
}
return nil
}
// Start controller wait til it's ready
pb.controllerStarted.Add(1)
go pb.controller()
pb.controllerStarted.Wait()
// Inject some data, close the loader
pb.tsDataChan <- []TimeStamper{mockTsData{Tim: dataTime, Val: 6}}
time.Sleep(1 * time.Millisecond)
mts.Wg.Done()
pb.Pause()
time.Sleep(100 * time.Millisecond)
pb.Resume()
// Wait til data has been processed
pb.termWg.Wait()
// Make sure callback was called
if !callbackHit {
t.Errorf("Provided PlayBack call was not executed")
}
}
func TestLongPause(t *testing.T) {
// Create a new PlayBack at 2x rate
var mts mockTsBlockingDs
simStartTime := time.Now()
dataTime := simStartTime.Add(time.Second * 1)
pb, _ := New("test", simStartTime, dataTime, &mts, 2, nil)
pb.init()
// Callback measures time to first data playback send. Since
// the first time stamper is 1 second after playback start,
// the first callback should be at .5 seconds given the rate is 2x
callbackHit := false
pb.SendTs = func(ts TimeStamper) error {
callbackHit = true
wallDur := time.Since(pb.WallStartTime)
expDur := (dataTime.Sub(simStartTime) / 2) + (time.Millisecond * 523)
timeDrift := wallDur - expDur
if math.Abs(timeDrift.Seconds()*1000) > 3 {
t.Errorf("Time = %f(ms); want less than 3(ms)", timeDrift.Seconds()*1000)
}
if ts.(mockTsData).Val != 6 {
t.Errorf("Val = %d; want 6", ts.(mockTsData).Val)
}
return nil
}
// Start controller wait til it's ready
pb.controllerStarted.Add(1)
go pb.controller()
pb.controllerStarted.Wait()
// Inject some data, close the loader
pb.tsDataChan <- []TimeStamper{mockTsData{Tim: dataTime, Val: 6}}
time.Sleep(1 * time.Millisecond)
mts.Wg.Done()
pb.Pause()
time.Sleep(523 * time.Millisecond)
pb.Resume()
// Wait til data has been processed
pb.termWg.Wait()
// Make sure callback was called
if !callbackHit {
t.Errorf("Provided PlayBack call was not executed")
}
}
// TestSendSpeed confirms that a value sent into playback is sent within
// 3 milliseconds of the proper time
func TestSendSpeed(t *testing.T) {
// Create a new PlayBack at 2x rate
var mts mockSliceBackedDs
simStartTime := time.Now()
dataTime := simStartTime.Add(time.Second * 1)
pb, _ := New("test", simStartTime, dataTime, &mts, 2, nil)
pb.init()
// Callback measures time to first data playback send. Since
// the first time stamper is 1 second after playback start,
// the first callback should be at .5 seconds given the rate is 2x
callbackHit := false
pb.SendTs = func(ts TimeStamper) error {
callbackHit = true
wallDur := time.Since(pb.WallStartTime)
expDur := ts.GetTimeStamp().Sub(simStartTime) / 2
timeDrift := wallDur - expDur
if math.Abs(timeDrift.Seconds()*1000) > 3 {
t.Errorf("Time = %f(ms); want less than 3(ms)", timeDrift.Seconds()*1000)
}
if ts.(mockTsData).Val != 6 {
t.Errorf("Val = %d; want 6", ts.(mockTsData).Val)
}
return nil
}
// Create a timestamper with a timestamp 1 second out after
// start time and push it into the playback data chan
mts.TimeStampers = []TimeStamper{
mockTsData{Tim: dataTime, Val: 6},
mockTsData{Tim: simStartTime.Add(time.Second * 3), Val: 6},
}
// run dataTimer, it will execute callback
pb.controllerStarted.Add(1)
pb.controller()
pb.termWg.Wait()
// Make sure call was called
if !callbackHit {
t.Errorf("Provided PlayBack call was not executed")
}
}
// TestQuitDuringLongSleep forces dataTimer into a long sleep by
// providing one timestamper 5000 minutes out from PlayBack start time.
// During the sleep, test confirms that the Quit() command is responded
// to without delay.
func TestQuitDuringLongSleep(t *testing.T) {
mts := mockSliceBackedDs{}
simStartTime := time.Now()
dataTime := simStartTime.Add(time.Minute * 5000)
mts.TimeStampers = []TimeStamper{mockTsData{Tim: dataTime, Val: 6}}
pb, _ := New("test", simStartTime, dataTime, &mts, 1, nil)
//Startup controller
pb.controllerStarted.Add(1)
go pb.controller()
pb.controllerStarted.Wait()
// Wait until the dataTimer has had time to pick up
// the first TimeStamper data and is sleeping
time.Sleep(200 * time.Millisecond)
pb.Quit()
pb.Wait()
rt := time.Since(pb.WallStartTime) - (200 * time.Millisecond)
if rt > (time.Millisecond * 1) {
t.Errorf("Total PlayBack Time: %f(ms), Expected to be less than 3(ms)",
rt.Seconds()*1000)
}
// dataTimer goroutine should shut down within ~250ms of Quit()
select {
case _, ok := <-pb.timedTs:
// should be closed
if ok {
t.Error("tsDataChan is still open, expected it to be closed")
}
case <-time.After(275 * time.Millisecond):
t.Error("tsDataChan is still open, expected it to be closed")
}
}
func TestSameTimeStamp(t *testing.T) {
// Create a new PlayBack at 2x rate
var mts mockSliceBackedDs
simStartTime := time.Now()
dataTime := simStartTime.Add(time.Millisecond * 25)
mts.TimeStampers = make([]TimeStamper, 0, 250)
for i := 0; i < 250; i++ {
mts.TimeStampers = append(mts.TimeStampers,
mockTsData{Tim: dataTime, Val: 6})
}
pb, _ := New("test", simStartTime, dataTime, &mts, 1, nil)
pb.init()
cbCount := 0
cbDrifts := make([]time.Time, 250)
pb.SendTs = func(ts TimeStamper) error {
cbCount++
cbDrifts[cbCount-1] = time.Now()
return nil
}
// run send, it will execute callback
pb.controllerStarted.Add(1)
go pb.controller()
pb.Wait()
// Make sure callback was called
if cbCount != 250 {
t.Errorf("Provided PlayBack called %d, expected 250", cbCount)
}
// all 500 should fall withing 3ms of expected time
for i, td := range cbDrifts {
wallDur := td.Sub(pb.WallStartTime)
d := (wallDur - (25 * time.Millisecond)).Seconds() * 1000.0
if d > 3 {
t.Errorf("Time = %f(ms) index %d; want less than 3(ms)", d, i)
}
}
}
// Confirm pause works when called while PlayBack is waiting to send
// out next timestamper.
// For example, 2 timestamps in playback, 500ms in between packets.
// After processing the first ts, PlayBack "waits" for 500ms before
// sending out the second ts. During the wait, PlayBack should still
// respond to Quit() and Pause() API control signals.
// This test implements the above setup, and pauses for 100ms between
// ts1 and ts2. So ts2 should be sent out 600ms(100ms pause + 500ms) after
// sim start
func TestSendLongSleepPause(t *testing.T) {
// Create a new PlayBack at 2x rate
var mts mockSliceBackedDs
simStartTime := time.Now()
dataTime := simStartTime.Add(time.Millisecond * 25)
data2Time := simStartTime.Add(time.Millisecond * 425)
mts.TimeStampers = []TimeStamper{
mockTsData{Tim: dataTime, Val: 6},
mockTsData{Tim: data2Time, Val: 6},
}
pb, _ := New("test", simStartTime, dataTime, &mts, 1, nil)
pb.init()
cbChan := make(chan struct{})
// Callback measures time playback send. Since the first time
// stamper is 1 second after playback start, the first callback
// should be at .5 seconds given the rate is 2x
cbCount := 0
cbDrifts := make([]float64, 2)
pb.SendTs = func(ts TimeStamper) error {
cbCount++
// lets test know that 1st timestamper has been sent and pb is
// processing 2nd timestaper as soon as this call returns
if cbCount == 1 {
close(cbChan)
}
wallDur := time.Since(pb.WallStartTime)
expDur := ts.GetTimeStamp().Sub(simStartTime)
if cbCount == 2 {
expDur += (100 * time.Millisecond)
}
cbDrifts[cbCount-1] = (wallDur - expDur).Seconds() * 1000.0
return nil
}
// run send, it will execute callback
pb.controllerStarted.Add(1)
go pb.controller()
<-cbChan
time.Sleep(250 * time.Millisecond)
pb.Pause()
time.Sleep(100 * time.Millisecond)
pb.Resume()
pb.Wait()
// Make sure call was called
if cbCount != 2 {
t.Errorf("Provided PlayBack called %d, expected 2", cbCount)
}
for _, td := range cbDrifts {
if td > 3.0 {
t.Errorf("Time = %f(ms); want less than 3(ms)", td)
}
}
}
// TestSimRate confirms that the user provided sim rate is translated
// into PlayBacks simRateDur properly. A sim rate of 2x and a duration
// of 4mins should result in a sim duration of 2mins
func TestSimRate(t *testing.T) {
var mts mockTsDataSource
pb, _ := New("test", time.Now(), time.Now(), &mts, 2, nil)
dur := time.Duration(time.Minute * 4)
simTime := (dur / pb.rateDur)
if simTime.Minutes() != 2 {
t.Errorf("dur(4) / 2 = %f; want 2", simTime.Minutes())
}
}
func TestLoadTsData(t *testing.T) {
// Create a new mocked data source that emits 23 time stamper values
mts := mockTsDataSource{MaxRecs: 23}
// Create a new playback that uses mts
pb, _ := New("test", time.Now(), time.Now(), &mts, 2, nil)
pb.init()
// Set a read buffer size of 10
pb.tsDataBufSize = 10
// load data into the chan
go pb.loadTimeStampedData()
readCnt := 0
bufLens := [6]int{10, 10, 3}
// Read the data in the chan
for dataBuf := range pb.tsDataChan {
readCnt++
if len(dataBuf) != bufLens[readCnt-1] {
t.Errorf("buf %d length: %d; expected %d",
readCnt,
len(dataBuf),
bufLens[readCnt-1])
}
}
//Should have 3 reads from the chan
if readCnt != 3 {
t.Errorf("Got %d Chan reads; expected 3", readCnt)
}
}
func TestCreateNoSource(t *testing.T) {
_, err := New("test", time.Now(), time.Now(), nil, 2, nil)
if err == nil {
t.Errorf("Got Empty error, expected error")
}
expected := "playBack: tsSource required"
if err.Error() != "playBack: tsSource required" {
t.Errorf("Got %s error, expected %s", err.Error(), expected)
}
}
func TestPlay(t *testing.T) {
mts := mockTsBlockingDs{}
// Create a new playback that uses mts
pb, _ := New("test", time.Now(), time.Now(), &mts, 2, nil)
// Active flag should start as false
if pb.replayActive {
t.Errorf("replay active true, expected false")
}
pb.Play()
time.Sleep(10 * time.Millisecond)
// play worked if it set active flag to true
if !pb.replayActive {
t.Errorf("replay active false, expected true")
}
// Release mts so we don't leak loader goroutine
mts.Wg.Done()
// play should start data loading from TimeStamper Source, so
// confirm source's Next() was called
if !mts.NextCalled {
t.Error("NextCalled is false, expected true")
}
// Ok at this point, no data was loaded, dataloader should be
// closing, and sender should be closing and releasing PlayBacks
// Blocking wait
pb.Wait()
// Make sure loader closed dat chan to loader confirm exit-cleanup
select {
case _, ok := <-pb.tsDataChan:
// should be closed with no data
if ok {
t.Error("tsDataChan was not empty, expected it to be empty")
}
default:
t.Error("tsDataChan is still open, expected it to be closed")
}
}
func TestPause(t *testing.T) {
// Create a new mocked data source that emits 23 time stamper values
mts := mockTsBlockingDs{}
// Create a new playback that uses mts
pb, _ := New("test", time.Now(), time.Now(), &mts, 2, nil)
// Need a pause chan for Pause() to signal
pb.pauseChan = make(chan struct{})
// Create a closed resumeChan, this is
// a possible state after a pause-resume cycle
pb.resumeChan = make(chan struct{})
close(pb.resumeChan)
pb.replayActive = true
pb.paused = false
pb.Pause()
// Make sure pause closed pauseChan to signal a pause
select {
case _, ok := <-pb.pauseChan:
// should be closed with no data
if ok {
t.Error("pauseChan was not empty, expected it to be empty")
}
default:
t.Error("pauseChan is still open, expected it to be closed")
}
// Pause worked if it set active flag to true
if !pb.paused {
t.Error("pause flag is false, expected true")
}
select {
case _, ok := <-pb.resumeChan:
if !ok {
t.Error("resumeChan is closed, expected it to be open")
}
default:
}
}
func TestPauseAlreadyPaused(t *testing.T) {
// Create a new mocked data source that emits 23 time stamper values
mts := mockTsBlockingDs{}
// Create a new playback that uses mts
pb, _ := New("test", time.Now(), time.Now(), &mts, 2, nil)
pb.pauseChan = make(chan struct{})
pb.replayActive = false
pb.paused = true
pb.Pause()
// Since pb is already in the paused state,
// Pause() should do nothing
select {
case <-pb.pauseChan:
t.Error("pauseChan signaled, expected to be un-signaled")
default:
}
if pb.replayActive {
t.Error("replay active true, expected to be false")
}
if !pb.paused {
t.Error("paused false, expected to be true")
}
}
func TestResume(t *testing.T) {
// Create a new mocked data source that emits 23 time stamper values
mts := mockTsBlockingDs{}
// Create a new playback that uses mts
pb, _ := New("test", time.Now(), time.Now(), &mts, 2, nil)
// Need a resume chan for Resume() to signal
pb.resumeChan = make(chan struct{})
// Create a closed pauseChan, this is
// a possible state after a pause
pb.pauseChan = make(chan struct{})
close(pb.pauseChan)
pb.paused = true
pb.Resume()
// Make sure resume closed resumeChan to signal a pause
select {
case _, ok := <-pb.resumeChan:
// should be closed with no data
if ok {
t.Error("resumeChan was not empty, expected it to be empty")
}
default:
t.Error("resumeChan is still open, expected it to be closed")
}
// Pause worked if it set active flag to true
if pb.paused {
t.Error("pause flag is false, expected true")
}
select {
case _, ok := <-pb.pauseChan:
if !ok {
t.Error("pausehan is closed, expected it to be open")
}
default:
}
}
func TestQuit(t *testing.T) {
mts := mockTsBlockingDs{}
// Create a new playback that uses mts
pb, _ := New("test", time.Now(), time.Now(), &mts, 2, nil)
pb.replayActive = true
pb.quitChan = make(chan struct{})
pb.Quit()
select {
case <-pb.quitChan:
default:
t.Error("quitChan not signaled, expected it to be signaled")
}
}