@@ -415,3 +415,84 @@ func TestQueue_Err(t *testing.T) {
415415 })
416416 }
417417}
418+
419+ func TestQueue_Selftest (t * testing.T ) {
420+ setNowFunc (func () time.Time {
421+ t , _ := time .Parse (time .DateTime , "2024-11-04 15:04:05" )
422+ return t
423+ })
424+
425+ tests := []struct {
426+ name string
427+ topic string
428+ error1 error
429+ error2 error
430+ }{
431+ {
432+ name : "Success" ,
433+ topic : "" ,
434+ },
435+ {
436+ name : "Success with topic" ,
437+ topic : "user.delete" ,
438+ },
439+ {
440+ name : "Reschedule failed" ,
441+ topic : "" ,
442+ error1 : errors .New ("FindOneAndUpdate1" ),
443+ },
444+ {
445+ name : "Set maxtries to error failed" ,
446+ topic : "" ,
447+ error2 : errors .New ("FindOneAndUpdate2" ),
448+ },
449+ }
450+
451+ for _ , tt := range tests {
452+ t .Run (tt .name , func (t * testing.T ) {
453+ dbMock := NewDbInterfaceMock (t )
454+
455+ q := NewQueue (dbMock )
456+
457+ query1 := bson.M {
458+ "state" : StateRunning ,
459+ "meta.dispatched" : bson.M {"$lt" : nowFunc ().Add (DefaultTimeout )},
460+ }
461+
462+ if tt .topic != "" {
463+ query1 ["topic" ] = tt .topic
464+ }
465+
466+ dbMock .EXPECT ().UpdateMany (query1 ,
467+ bson.M {"$set" : bson.M {
468+ "state" : StatePending ,
469+ "meta.dispatched" : nil },
470+ }).Return (tt .error1 )
471+
472+ query2 := bson.M {
473+ "state" : StatePending ,
474+ "$expr" : bson.M {"$gte" : bson.A {"$tries" , "$maxtries" }},
475+ }
476+
477+ if tt .topic != "" {
478+ query2 ["topic" ] = tt .topic
479+ }
480+
481+ dbMock .EXPECT ().UpdateMany (query2 ,
482+ bson.M {"$set" : bson.M {
483+ "state" : StateError ,
484+ "meta.completed" : nowFunc ()},
485+ }).Return (tt .error2 )
486+
487+ err := q .Selfcare (tt .topic )
488+
489+ if tt .error1 != nil {
490+ assert .Equal (t , tt .error1 , err )
491+ } else if tt .error2 != nil {
492+ assert .Equal (t , tt .error2 , err )
493+ } else {
494+ assert .Equal (t , nil , err )
495+ }
496+ })
497+ }
498+ }
0 commit comments