From f305b106f951e406affbbc67bbd6e03ce6a46295 Mon Sep 17 00:00:00 2001 From: Cristian Maglie Date: Fri, 13 Sep 2024 12:26:10 +0200 Subject: [PATCH] Added unit tests --- client_test.go | 56 ++++++++++++++++++++++++++++++++++++ dummy-discovery/args/args.go | 9 ++++++ 2 files changed, 65 insertions(+) diff --git a/client_test.go b/client_test.go index ce945ee..abf08ce 100644 --- a/client_test.go +++ b/client_test.go @@ -19,6 +19,7 @@ package discovery import ( "fmt" + "io" "net" "testing" "time" @@ -93,3 +94,58 @@ func TestDiscoveryStdioHandling(t *testing.T) { require.False(t, disc.Alive()) } + +func TestClient(t *testing.T) { + // Build dummy-discovery + builder, err := paths.NewProcess(nil, "go", "build") + require.NoError(t, err) + builder.SetDir("dummy-discovery") + require.NoError(t, builder.Run()) + + t.Run("WithDiscoveryCrashingOnStartup", func(t *testing.T) { + // Run client with discovery crashing on startup + cl := NewClient("1", "dummy-discovery/dummy-discovery", "--invalid") + require.ErrorIs(t, cl.Run(), io.EOF) + }) + + t.Run("WithDiscoveryCrashingWhileSendingCommands", func(t *testing.T) { + // Run client with crashing discovery after 1 second + cl := NewClient("1", "dummy-discovery/dummy-discovery", "-k") + require.NoError(t, cl.Run()) + + time.Sleep(time.Second) + + ch, err := cl.StartSync(20) + require.Error(t, err) + require.Nil(t, ch) + }) + + t.Run("WithDiscoveryCrashingWhileStreamingEvents", func(t *testing.T) { + // Run client with crashing discovery after 1 second + cl := NewClient("1", "dummy-discovery/dummy-discovery", "-k") + require.NoError(t, cl.Run()) + + ch, err := cl.StartSync(20) + require.NoError(t, err) + + time.Sleep(time.Second) + + loop: + for { + select { + case msg, ok := <-ch: + if !ok { + // Channel closed: Test passed + fmt.Println("Event channel closed") + break loop + } + fmt.Println("Recv: ", msg) + case <-time.After(time.Second): + t.Error("Crashing client did not close event channel") + break loop + } + } + + cl.Quit() + }) +} diff --git a/dummy-discovery/args/args.go b/dummy-discovery/args/args.go index 8b1423e..f7b8195 100644 --- a/dummy-discovery/args/args.go +++ b/dummy-discovery/args/args.go @@ -20,6 +20,7 @@ package args import ( "fmt" "os" + "time" ) // Tag is the current git tag @@ -38,6 +39,14 @@ func Parse() { fmt.Printf("dummy-discovery %s (build timestamp: %s)\n", Tag, Timestamp) os.Exit(0) } + if arg == "-k" { + // Emulate crashing discovery + go func() { + time.Sleep(time.Millisecond * 500) + os.Exit(1) + }() + continue + } fmt.Fprintf(os.Stderr, "invalid argument: %s\n", arg) os.Exit(1) }