-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessor_test.go
More file actions
732 lines (630 loc) · 25.1 KB
/
processor_test.go
File metadata and controls
732 lines (630 loc) · 25.1 KB
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
package main
import (
"context"
"encoding/json"
"fmt"
"sync"
"testing"
"time"
"github.com/rabbitmq/amqp091-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"gorm.io/gorm"
)
// Helper untuk setup processor test
func setupProcessorTest(t *testing.T) (*QueueProcessor, *MockPublisher, *MockCloser, *MockRestAPI, *gorm.DB, func()) {
db, dbCleanup := setupTestDatabase(t)
mockCloser := NewMockCloser(t)
mockPublisher := NewMockPublisher(t)
mockAPI := NewMockRestAPI(t)
processor, err := NewQueueProcessor(
nil, // config is not needed in this test
db,
mockAPI,
WithConnection(mockCloser), WithChannel(mockPublisher),
)
assert.NoError(t, err)
// Mock Close() for cleanup to prevent unexpected calls
mockPublisher.EXPECT().Close().Return(nil).Maybe()
mockCloser.EXPECT().Close().Return(nil).Maybe()
cleanup := func() {
processor.Stop()
dbCleanup()
}
return processor, mockPublisher, mockCloser, mockAPI, db, cleanup
}
func TestQueueProcessor_ProcessEligibleQueue(t *testing.T) {
t.Run("POSITIVE-Success", func(t *testing.T) {
processor, _, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
queue := &Queue{Name: "q-success", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
err := processor.ProcessEligibleQueue(context.Background())
assert.NoError(t, err)
var updated Queue
_ = db.First(&updated, queue.ID).Error
assert.Equal(t, StatusCompleted, updated.Status)
assert.Equal(t, 0, updated.RetryCount)
mockAPI.AssertExpectations(t)
})
t.Run("NEGATIVE-Failure", func(t *testing.T) {
processor, _, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
queue := &Queue{Name: "q-fail", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
errFail := assert.AnError
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(errFail).Once()
err := processor.ProcessEligibleQueue(context.Background())
assert.Error(t, err)
var updated Queue
_ = db.First(&updated, queue.ID).Error
assert.Equal(t, StatusFailed, updated.Status)
assert.Equal(t, 1, updated.RetryCount)
assert.True(t, updated.LastRetryAt.Valid)
mockAPI.AssertExpectations(t)
})
t.Run("NEGATIVE-EmptyQueue", func(t *testing.T) {
processor, _, _, mockAPI, _, cleanup := setupProcessorTest(t)
defer cleanup()
err := processor.ProcessEligibleQueue(context.Background())
assert.NoError(t, err)
// Nothing to assert in DB, just make sure no panic/error
mockAPI.AssertExpectations(t)
})
t.Run("POSITIVE-ChainProcessing", func(t *testing.T) {
processor, mockPublisher, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
for i := range 3 {
_ = repo.Save(context.Background(), &Queue{Name: fmt.Sprintf("q-%d", i), Status: StatusPending})
}
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Times(3)
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(nil).Maybe()
for range 3 {
err := processor.ProcessEligibleQueue(context.Background())
assert.NoError(t, err)
}
var queues []Queue
db.Find(&queues)
for _, q := range queues {
assert.Equal(t, StatusCompleted, q.Status)
}
mockAPI.AssertExpectations(t)
})
t.Run("NEGATIVE-GetEligibleQueues_DBError", func(t *testing.T) {
processor, _, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
// Close DB to simulate error
sqlDB, _ := db.DB()
sqlDB.Close()
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Maybe()
err := processor.ProcessEligibleQueue(context.Background())
assert.Error(t, err)
})
t.Run("NEGATIVE-SaveQueue_DBError", func(t *testing.T) {
processor, _, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
queue := &Queue{Name: "q-db-error", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Run(func(queue *Queue) {
sqlDB, _ := db.DB()
sqlDB.Close()
}).Return(nil).Once()
err := processor.ProcessEligibleQueue(context.Background())
assert.Error(t, err)
})
t.Run("NEGATIVE-SimulateProcessingErr_SaveQueueDBError", func(t *testing.T) {
processor, _, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
queue := &Queue{Name: "q-db-error", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Run(func(queue *Queue) {
sqlDB, _ := db.DB()
sqlDB.Close()
}).Return(assert.AnError).Once()
err := processor.ProcessEligibleQueue(context.Background())
assert.Error(t, err)
})
t.Run("NEGATIVE-ChainProcessing_DBError", func(t *testing.T) {
processor, mockPublisher, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
// Insert 2 queue
_ = repo.Save(context.Background(), &Queue{Name: "q1", Status: StatusPending})
_ = repo.Save(context.Background(), &Queue{Name: "q2", Status: StatusPending})
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(nil).Maybe()
// Close DB after first process, before chain
err := processor.ProcessEligibleQueue(context.Background())
assert.NoError(t, err)
sqlDB, _ := db.DB()
sqlDB.Close()
err = processor.ProcessEligibleQueue(context.Background())
assert.Error(t, err)
})
t.Run("NEGATIVE-PublishWithContextError", func(t *testing.T) {
processor, mockPublisher, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
queue := &Queue{Name: "q-pub-error", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Twice()
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(assert.AnError).Once()
// Insert 2 queue biar chain processing jalan
_ = repo.Save(context.Background(), &Queue{Name: "q-pub-error2", Status: StatusPending})
err := processor.ProcessEligibleQueue(context.Background())
assert.NoError(t, err) // proses pertama sukses
err = processor.ProcessEligibleQueue(context.Background())
assert.NoError(t, err) // proses kedua tetap jalan, error publish hanya log
})
t.Run("NEGATIVE-ProcessEligibleQueue_SaveFailedQueueError", func(t *testing.T) {
processor, _, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
queue := &Queue{Name: "q-save-fail", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(assert.AnError).Once().Run(func(args mock.Arguments) {
// Simulate DB error on Save after processing fails
sqlDB, _ := db.DB()
sqlDB.Close()
})
err := processor.ProcessEligibleQueue(context.Background())
assert.Error(t, err)
assert.Contains(t, err.Error(), "sql: database is closed")
})
t.Run("NEGATIVE-ProcessEligibleQueue_SaveCompletedQueueError", func(t *testing.T) {
processor, _, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
queue := &Queue{Name: "q-save-completed-fail", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once().Run(func(args mock.Arguments) {
// Simulate DB error on Save after processing succeeds
sqlDB, _ := db.DB()
sqlDB.Close()
})
err := processor.ProcessEligibleQueue(context.Background())
assert.Error(t, err)
assert.Contains(t, err.Error(), "sql: database is closed")
})
t.Run("NEGATIVE-ProcessEligibleQueue_HasRemainingQueuesError", func(t *testing.T) {
processor, _, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
queue := &Queue{Name: "q-has-remaining-fail", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once().Run(func(args mock.Arguments) {
// Simulate DB error on HasRemainingQueues
// This requires mocking the repository, which is already done in setupProcessorTest
// We need to make repo.HasRemainingQueues return an error.
// This is tricky because repo is created inside NewQueueProcessor.
// A simpler way is to close the DB connection before calling HasRemainingQueues.
sqlDB, _ := db.DB()
sqlDB.Close()
})
err := processor.ProcessEligibleQueue(context.Background())
assert.Error(t, err)
assert.Contains(t, err.Error(), "sql: database is closed")
})
}
func TestQueueProcessor_TriggerProcessing(t *testing.T) {
t.Run("POSITIVE-PublishSuccess", func(t *testing.T) {
processor, mockPublisher, _, _, _, cleanup := setupProcessorTest(t)
defer cleanup()
mockPublisher.EXPECT().
PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).
Return(nil).Once()
err := processor.TriggerProcessing(context.Background())
assert.NoError(t, err)
mockPublisher.AssertExpectations(t)
})
t.Run("NEGATIVE-PublishError", func(t *testing.T) {
processor, mockPublisher, _, _, _, cleanup := setupProcessorTest(t)
defer cleanup()
errExpected := assert.AnError
mockPublisher.EXPECT().
PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).
Return(errExpected).Once()
err := processor.TriggerProcessing(context.Background())
assert.Error(t, err)
assert.Equal(t, errExpected, err)
mockPublisher.AssertExpectations(t)
})
t.Run("NEGATIVE-MarshalError", func(t *testing.T) {
processor, _, _, _, _, cleanup := setupProcessorTest(t)
defer cleanup()
// Temporarily replace json.Marshal to force an error
originalMarshal := json.Marshal
jsonMarshal = func(v any) ([]byte, error) {
return nil, assert.AnError
}
defer func() {
jsonMarshal = originalMarshal
}()
err := processor.TriggerProcessing(context.Background())
assert.Error(t, err)
assert.Equal(t, assert.AnError, err)
})
}
func TestQueueProcessor_triggerNextProcessing(t *testing.T) {
t.Run("NEGATIVE-MarshalError", func(t *testing.T) {
processor, _, _, _, _, cleanup := setupProcessorTest(t)
defer cleanup()
// Temporarily replace json.Marshal to force an error
originalMarshal := jsonMarshal
jsonMarshal = func(v any) ([]byte, error) {
return nil, assert.AnError
}
defer func() {
jsonMarshal = originalMarshal
}()
err := processor.triggerNextProcessing(context.Background())
assert.Error(t, err)
assert.Equal(t, assert.AnError, err)
})
}
func TestQueueProcessor_Start_ConsumeError(t *testing.T) {
t.Run("NEGATIVE-ConsumeError_ReturnsError", func(t *testing.T) {
processor, mockPublisher, _, _, _, cleanup := setupProcessorTest(t)
defer cleanup()
mockPublisher.EXPECT().Consume(mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil, assert.AnError).Once()
err := processor.Start()
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to register RabbitMQ consumer")
})
}
func TestQueueProcessor_Stop(t *testing.T) {
// Re-setup mocks without using the shared setupProcessorTest to avoid
// conflicting/duplicate mock expectations on the .Close() method.
db, dbCleanup := setupTestDatabase(t)
defer dbCleanup()
mockCloser := NewMockCloser(t)
mockPublisher := NewMockPublisher(t)
mockAPI := NewMockRestAPI(t)
processor, err := NewQueueProcessor(
nil, // config is not needed in this test
db,
mockAPI,
WithConnection(mockCloser), WithChannel(mockPublisher),
)
assert.NoError(t, err)
// Set clear expectations for this specific test.
mockPublisher.EXPECT().Close().Return(nil).Once()
mockCloser.EXPECT().Close().Return(nil).Once()
// Execute the function under test.
processor.Stop()
// Assert that the expectations were met.
mockPublisher.AssertExpectations(t)
mockCloser.AssertExpectations(t)
}
func TestNewQueueProcessor_ConfigRequired(t *testing.T) {
t.Run("NEGATIVE-ConfigNil_ReturnsError", func(t *testing.T) {
db, cleanupDB := setupTestDatabase(t)
defer cleanupDB()
apiMock := NewMockRestAPI(t)
processor, err := NewQueueProcessor(nil, db, apiMock)
assert.Error(t, err)
assert.EqualError(t, err, "config is required for production setup")
assert.Nil(t, processor)
})
}
// mockAcknowledger implements the amqp091.Acknowledger interface for testing.
type mockAcknowledger struct {
acked chan bool
nacked chan bool
}
func (a *mockAcknowledger) Ack(tag uint64, multiple bool) error {
// In this test, we don't expect Ack to be called, but it's good practice to implement it.
// For simplicity, we won't signal anything here.
return nil
}
func (a *mockAcknowledger) Nack(tag uint64, multiple bool, requeue bool) error {
// Signal that Nack was called.
a.nacked <- true
return nil
}
func (a *mockAcknowledger) Reject(tag uint64, requeue bool) error {
// In this test, we don't expect Reject to be called.
return nil
}
func TestQueueProcessor_Start(t *testing.T) {
t.Run("POSITIVE-ProcessMessage", func(t *testing.T) {
processor, mockPublisher, _, mockAPI, db, cleanup := setupProcessorTest(t)
defer cleanup()
// Setup: insert eligible queue
repo := NewRepository(db)
queue := &Queue{Name: "start-queue", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
// Setup mock Consume
msgCh := make(chan amqp091.Delivery, 1)
mockPublisher.EXPECT().Consume(
"queue_processing", "", false, false, false, false, mock.Anything,
).Return((<-chan amqp091.Delivery)(msgCh), nil).Once()
// Setup mock SimulateProcessing
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(nil).Maybe()
// Run Start in a goroutine and wait for it to complete
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
processor.Start()
}()
// Insert a dummy message
msgCh <- amqp091.Delivery{}
close(msgCh)
wg.Wait() // Wait for the processor to finish
// Assert effects: status queue should be Completed
var updated Queue
_ = db.First(&updated, queue.ID).Error
assert.Equal(t, StatusCompleted, updated.Status)
mockPublisher.AssertExpectations(t)
mockAPI.AssertExpectations(t)
})
t.Run("NEGATIVE-ProcessEligibleQueueError_NackMessage", func(t *testing.T) {
processor, mockPublisher, _, mockAPI, db, _ := setupProcessorTest(t)
// No defer cleanup() here because we need to control the Stop() call manually.
repo := NewRepository(db)
queue := &Queue{Name: "start-nack", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
// Setup the mock acknowledger to spy on Nack calls.
acknowledger := &mockAcknowledger{
nacked: make(chan bool, 1),
}
// Create a delivery message with our mock acknowledger.
delivery := amqp091.Delivery{
Acknowledger: acknowledger,
Body: []byte("test message"),
}
msgCh := make(chan amqp091.Delivery, 1)
msgCh <- delivery
mockPublisher.EXPECT().Consume(
"queue_processing", "", false, false, false, false, mock.Anything,
).Return((<-chan amqp091.Delivery)(msgCh), nil).Once()
mockAPI.EXPECT().SimulateProcessing(mock.Anything).Return(assert.AnError).Once()
// Run Start in a goroutine.
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
processor.Start()
}()
select {
case <-acknowledger.nacked:
// Success: Nack was called as expected.
case <-time.After(2 * time.Second):
assert.Fail(t, "timed out waiting for Nack to be called")
}
// Manually stop the processor and wait for the goroutine to exit.
close(msgCh)
processor.Stop()
wg.Wait()
// Final assertions.
mockPublisher.AssertExpectations(t)
mockAPI.AssertExpectations(t)
})
}
func TestQueueProcessor_INTEGRATION_ShiftingQueue_AntiStarvation(t *testing.T) {
processor, mockPublisher, _, apiMock, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(nil).Maybe()
baseTime := time.Now().Add(-1 * time.Hour)
queue1 := &Queue{Name: "queue-oldest", Status: StatusPending}
_ = repo.Save(context.Background(), queue1)
db.Model(queue1).Update("created_at", baseTime)
queue2 := &Queue{Name: "queue-middle", Status: StatusPending}
_ = repo.Save(context.Background(), queue2)
db.Model(queue2).Update("created_at", baseTime.Add(30*time.Minute))
queue3 := &Queue{Name: "queue-newest", Status: StatusPending}
_ = repo.Save(context.Background(), queue3)
db.Model(queue3).Update("created_at", baseTime.Add(60*time.Minute))
// Step 1: Process (should get oldest, fail)
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(assert.AnError).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Step 2: Process (should get middle, success)
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Step 3: Process (should get newest, success)
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Step 4: Process (should get failed oldest again, success)
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Cek status akhir queue di DB
var q1, q2, q3 Queue
_ = db.Where("name = ?", "queue-oldest").First(&q1).Error
_ = db.Where("name = ?", "queue-middle").First(&q2).Error
_ = db.Where("name = ?", "queue-newest").First(&q3).Error
assert.Equal(t, StatusCompleted, q1.Status)
assert.Equal(t, StatusCompleted, q2.Status)
assert.Equal(t, StatusCompleted, q3.Status)
}
func TestQueueProcessor_INTEGRATION_Starvation_BurstInsert(t *testing.T) {
processor, mockPublisher, _, apiMock, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(nil).Maybe()
// Step 1: Insert satu queue gagal
queueFail := &Queue{Name: "queue-fail", Status: StatusPending}
_ = repo.Save(context.Background(), queueFail)
// Step 2: Insert 10 queue baru
for i := 0; i < 10; i++ {
q := &Queue{Name: fmt.Sprintf("queue-burst-%d", i), Status: StatusPending}
_ = repo.Save(context.Background(), q)
}
// Step 3: Fail queue-fail di proses pertama
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(assert.AnError).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Step 4: Semua queue lain success
for i := 0; i < 10; i++ {
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
}
// Step 5: Retry queue-fail, success
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Step 6: Assert queue-fail completed
var qf Queue
_ = db.Where("name = ?", "queue-fail").First(&qf).Error
assert.Equal(t, StatusCompleted, qf.Status)
assert.Equal(t, 1, qf.RetryCount)
}
func TestQueueProcessor_INTEGRATION_MultipleFailures_RetryCount(t *testing.T) {
processor, mockPublisher, _, apiMock, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(nil).Maybe()
queue := &Queue{Name: "queue-retry", Status: StatusPending}
_ = repo.Save(context.Background(), queue)
// Fail 2x
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(assert.AnError).Twice()
_ = processor.ProcessEligibleQueue(context.Background())
_ = processor.ProcessEligibleQueue(context.Background())
// Success
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Assert
var qr Queue
_ = db.Where("name = ?", "queue-retry").First(&qr).Error
assert.Equal(t, StatusCompleted, qr.Status)
assert.Equal(t, 2, qr.RetryCount)
}
func TestQueueProcessor_INTEGRATION_InterleavedSuccessFailure(t *testing.T) {
processor, mockPublisher, _, apiMock, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(nil).Maybe()
// Step 1: Insert Queue1 & Queue2
queue1 := &Queue{Name: "queue1", Status: StatusPending}
queue2 := &Queue{Name: "queue2", Status: StatusPending}
_ = repo.Save(context.Background(), queue1)
_ = repo.Save(context.Background(), queue2)
// Step 2: Queue1 gagal
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(assert.AnError).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Step 3: Queue2 sukses
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Step 4: Insert Queue3 setelah proses mulai
queue3 := &Queue{Name: "queue3", Status: StatusPending}
_ = repo.Save(context.Background(), queue3)
// Step 5: Queue1 retry sukses
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Step 6: Queue3 sukses
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
// Assert status akhir
var q1, q2, q3 Queue
_ = db.Where("name = ?", "queue1").First(&q1).Error
_ = db.Where("name = ?", "queue2").First(&q2).Error
_ = db.Where("name = ?", "queue3").First(&q3).Error
assert.Equal(t, StatusCompleted, q1.Status)
assert.Equal(t, 1, q1.RetryCount)
assert.Equal(t, StatusCompleted, q2.Status)
assert.Equal(t, 0, q2.RetryCount)
assert.Equal(t, StatusCompleted, q3.Status)
assert.Equal(t, 0, q3.RetryCount)
}
func TestQueueProcessor_INTEGRATION_AllQueuesFailedThenSucceed(t *testing.T) {
processor, mockPublisher, _, apiMock, db, cleanup := setupProcessorTest(t)
defer cleanup()
repo := NewRepository(db)
mockPublisher.EXPECT().PublishWithContext(mock.Anything, "", "queue_processing", false, false, mock.Anything).Return(nil).Maybe()
// Step 1: Insert 3 queue
queues := []*Queue{
{Name: "fail1", Status: StatusPending},
{Name: "fail2", Status: StatusPending},
{Name: "fail3", Status: StatusPending},
}
for _, q := range queues {
_ = repo.Save(context.Background(), q)
}
// Step 2: Semua gagal
for range 3 {
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(assert.AnError).Once()
_ = processor.ProcessEligibleQueue(context.Background())
}
// Step 3: Semua retry sukses
for range 3 {
apiMock.EXPECT().SimulateProcessing(mock.Anything).Return(nil).Once()
_ = processor.ProcessEligibleQueue(context.Background())
}
// Assert status akhir dan retry count
for _, name := range []string{"fail1", "fail2", "fail3"} {
var q Queue
_ = db.Where("name = ?", name).First(&q).Error
assert.Equal(t, StatusCompleted, q.Status)
assert.Equal(t, 1, q.RetryCount)
}
}
// --- END: Shifting/Anti-Starvation tests ---
func TestFakeAPI_SimulateProcessing(t *testing.T) {
t.Run("Success", func(t *testing.T) {
api := &FakeAPI{
randFloat: func() float32 {
return 0.6 // < 0.7, should succeed
},
}
err := api.SimulateProcessing(nil)
assert.NoError(t, err)
})
t.Run("Failure", func(t *testing.T) {
api := &FakeAPI{
randFloat: func() float32 {
return 0.8 // >= 0.7, should fail
},
}
err := api.SimulateProcessing(nil)
assert.Error(t, err)
})
t.Run("Default rand", func(t *testing.T) {
api := &FakeAPI{}
// We can't predict the outcome, but we can ensure it doesn't panic
_ = api.SimulateProcessing(nil)
})
}
func TestNewQueueProcessor_RabbitMQChannelError(t *testing.T) {
t.Run("NEGATIVE-RabbitMQChannelError_ReturnsError", func(t *testing.T) {
db, cleanupDB := setupTestDatabase(t)
defer cleanupDB()
apiMock := NewMockRestAPI(t)
mockConn := NewMockCloser(t)
// Expect Channel() to be called and return an error
mockConn.EXPECT().Channel().Return(nil, assert.AnError).Once()
// Expect Close() to be called on the connection when Channel() fails
mockConn.EXPECT().Close().Return(nil).Once()
processor, err := NewQueueProcessor(nil, db, apiMock, WithConnection(mockConn))
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to open RabbitMQ channel")
assert.Nil(t, processor)
// Assert that all expectations on the mock connection were met
mockConn.AssertExpectations(t)
})
}
func TestNewQueueProcessor_RabbitMQDialError(t *testing.T) {
t.Run("NEGATIVE-RabbitMQDialError_ReturnsError", func(t *testing.T) {
// Use a config with an invalid RabbitMQ URL to force a dial error
cfg := &Config{
RabbitMQURL: "amqp://invalid-host:5672/",
Host: "localhost", // Dummy values for other required fields
Port: 5432,
User: "user",
Password: "pass",
Name: "dbname",
}
db, cleanupDB := setupTestDatabase(t)
defer cleanupDB()
apiMock := NewMockRestAPI(t)
processor, err := NewQueueProcessor(cfg, db, apiMock)
assert.Error(t, err)
assert.Contains(t, err.Error(), "failed to connect to RabbitMQ")
assert.Nil(t, processor)
})
}