From 61b1da7807ddf12258bd61692a73a9a729af5c7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Jochum?= Date: Mon, 26 Sep 2022 12:37:17 +0200 Subject: [PATCH] Forgot to add test --- registry_test.go | 121 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 121 insertions(+) create mode 100644 registry_test.go diff --git a/registry_test.go b/registry_test.go new file mode 100644 index 0000000..292920b --- /dev/null +++ b/registry_test.go @@ -0,0 +1,121 @@ +package components + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/urfave/cli/v2" + "go-micro.dev/v4" +) + +type TestHandler struct { + initialized bool + name string + priority int + TimeInit time.Time + TimeStop time.Time +} + +func newTestHandler(name string, priority int) *TestHandler { + return &TestHandler{name: name, priority: priority} +} + +func (h *TestHandler) Name() string { + return h.name +} + +func (h *TestHandler) Priority() int { + return h.priority +} + +func (h *TestHandler) Initialized() bool { + return h.initialized +} + +func (h *TestHandler) Init(components *Registry, cli *cli.Context) error { + if h.initialized { + return errors.New("already initialized") + } + + h.TimeInit = time.Now() + + h.initialized = true + return nil +} + +func (h *TestHandler) Stop() error { + if !h.initialized { + return errors.New("not initialized") + } + + h.TimeStop = time.Now() + + h.initialized = false + return nil +} + +func (h *TestHandler) Flags(r *Registry) []cli.Flag { + return []cli.Flag{} +} + +func (h *TestHandler) Health(context context.Context) error { + return nil +} + +func TestInitSorting(t *testing.T) { + h1 := newTestHandler("Test1", 1) + h2 := newTestHandler("Test2", 5) + + service := micro.NewService() + cReg := New(service, "test", h2, h1) + + cli := &cli.Context{} + if err := cReg.Init(cli); err != nil { + t.Error(err) + return + } + + if h2.TimeInit.Before(h1.TimeInit) { + t.Error("Test has been initialized before Test1") + return + } +} + +func TestStopBeforeInit(t *testing.T) { + h1 := newTestHandler("Test1", 1) + h2 := newTestHandler("Test2", 5) + + service := micro.NewService() + cReg := New(service, "test", h1, h2) + + if err := cReg.Stop(); err == nil { + t.Error("Stop must fail if there was no init before") + return + } +} + +func TestStopSorting(t *testing.T) { + h1 := newTestHandler("Test1", 1) + h2 := newTestHandler("Test2", 5) + + service := micro.NewService() + cReg := New(service, "test", h2, h1) + + cli := &cli.Context{} + if err := cReg.Init(cli); err != nil { + t.Error(err) + return + } + + if err := cReg.Stop(); err != nil { + t.Error(err) + return + } + + if h1.TimeStop.Before(h2.TimeStop) { + t.Error("Test has been initialized before Test1") + return + } +}