tractor.dev/toolkit-go@v0.0.0-20241010005851-214d91207d07/engine/daemon/daemon_test.go (about)

     1  package daemon_test
     2  
     3  import (
     4  	"context"
     5  	"log/slog"
     6  	"testing"
     7  	"time"
     8  
     9  	"tractor.dev/toolkit-go/engine"
    10  	"tractor.dev/toolkit-go/engine/daemon"
    11  )
    12  
    13  type initService struct {
    14  	used bool
    15  }
    16  
    17  func (s *initService) InitializeDaemon() error {
    18  	s.used = true
    19  	return nil
    20  }
    21  
    22  type termService struct {
    23  	used bool
    24  }
    25  
    26  func (s *termService) TerminateDaemon(ctx context.Context) error {
    27  	s.used = true
    28  	return nil
    29  }
    30  
    31  type simpleService struct {
    32  	used bool
    33  }
    34  
    35  func (s *simpleService) Serve(ctx context.Context) {
    36  	s.used = true
    37  	return
    38  }
    39  
    40  func fatal(t *testing.T, err error) {
    41  	if err != nil {
    42  		t.Fatal(err)
    43  	}
    44  }
    45  
    46  func TestDaemon(t *testing.T) {
    47  	s1 := new(initService)
    48  	s2 := new(simpleService)
    49  	s3 := new(termService)
    50  
    51  	r, _ := engine.New()
    52  	fatal(t, r.Add(s1, s2, s3, slog.Default()))
    53  
    54  	d := &daemon.Framework{}
    55  	r.Assemble(d)
    56  
    57  	if len(d.Initializers) != 1 {
    58  		t.Fatal("initializer not registered")
    59  	}
    60  	if len(d.Terminators) != 1 {
    61  		t.Fatal("terminator not registered")
    62  	}
    63  	if len(d.Services) != 1 {
    64  		t.Fatal("service not registered")
    65  	}
    66  
    67  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Millisecond)
    68  	defer cancel()
    69  	fatal(t, d.Run(ctx))
    70  
    71  	if !s1.used {
    72  		t.Fatal("init not used")
    73  	}
    74  	if !s2.used {
    75  		t.Fatal("service not used")
    76  	}
    77  	if !s3.used {
    78  		t.Fatal("terminator not used")
    79  	}
    80  }