84 lines
1.8 KiB
Go
84 lines
1.8 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"sync/atomic"
|
|
"testing"
|
|
"time"
|
|
|
|
"household-book/model"
|
|
)
|
|
|
|
func TestNewBackupServiceUsesProductionSchedule(t *testing.T) {
|
|
svc := NewBackupService(nil, "book.db")
|
|
if svc.startupDelay != 30*time.Second {
|
|
t.Fatalf("startup delay=%s, want 30s", svc.startupDelay)
|
|
}
|
|
if svc.checkInterval != 6*time.Hour {
|
|
t.Fatalf("check interval=%s, want 6h", svc.checkInterval)
|
|
}
|
|
if svc.create == nil {
|
|
t.Fatal("scheduled create function is nil")
|
|
}
|
|
}
|
|
|
|
func TestBackupSchedulerCancellationDuringStartupDelay(t *testing.T) {
|
|
var calls atomic.Int32
|
|
svc := &BackupService{
|
|
startupDelay: time.Hour,
|
|
checkInterval: time.Hour,
|
|
create: func(context.Context) (*model.BackupStatus, error) {
|
|
calls.Add(1)
|
|
return nil, nil
|
|
},
|
|
}
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
done := make(chan struct{})
|
|
go func() {
|
|
svc.RunScheduler(ctx)
|
|
close(done)
|
|
}()
|
|
cancel()
|
|
|
|
select {
|
|
case <-done:
|
|
case <-time.After(200 * time.Millisecond):
|
|
t.Fatal("scheduler did not stop after context cancellation")
|
|
}
|
|
if got := calls.Load(); got != 0 {
|
|
t.Fatalf("create called %d times before startup delay elapsed", got)
|
|
}
|
|
}
|
|
|
|
func TestBackupSchedulerRunsAfterStartupDelay(t *testing.T) {
|
|
called := make(chan struct{}, 1)
|
|
svc := &BackupService{
|
|
startupDelay: time.Millisecond,
|
|
checkInterval: time.Hour,
|
|
create: func(context.Context) (*model.BackupStatus, error) {
|
|
called <- struct{}{}
|
|
return nil, nil
|
|
},
|
|
}
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
done := make(chan struct{})
|
|
go func() {
|
|
svc.RunScheduler(ctx)
|
|
close(done)
|
|
}()
|
|
|
|
select {
|
|
case <-called:
|
|
case <-time.After(200 * time.Millisecond):
|
|
t.Fatal("scheduler did not create backup after startup delay")
|
|
}
|
|
cancel()
|
|
select {
|
|
case <-done:
|
|
case <-time.After(200 * time.Millisecond):
|
|
t.Fatal("scheduler did not stop after context cancellation")
|
|
}
|
|
}
|