github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/internal/codespaces/grpc/client_test.go (about) 1 package grpc 2 3 import ( 4 "context" 5 "fmt" 6 "log" 7 "os" 8 "testing" 9 10 grpctest "github.com/ungtb10d/cli/v2/internal/codespaces/grpc/test" 11 ) 12 13 func startServer(t *testing.T) { 14 t.Helper() 15 if os.Getenv("GITHUB_ACTIONS") == "true" { 16 t.Skip("fails intermittently in CI: https://github.com/ungtb10d/cli/issues/5663") 17 } 18 19 ctx, cancel := context.WithCancel(context.Background()) 20 21 // Start the gRPC server in the background 22 go func() { 23 err := grpctest.StartServer(ctx) 24 if err != nil && err != context.Canceled { 25 log.Println(fmt.Errorf("error starting test server: %v", err)) 26 } 27 }() 28 29 // Stop the gRPC server when the test is done 30 t.Cleanup(func() { 31 cancel() 32 }) 33 } 34 35 func connect(t *testing.T) (client *Client) { 36 t.Helper() 37 38 client, err := Connect(context.Background(), &grpctest.Session{}, "token") 39 if err != nil { 40 t.Fatalf("error connecting to internal server: %v", err) 41 } 42 43 t.Cleanup(func() { 44 client.Close() 45 }) 46 47 return client 48 } 49 50 // Test that the gRPC client returns the correct port and URL when the JupyterLab server starts successfully 51 func TestStartJupyterServerSuccess(t *testing.T) { 52 startServer(t) 53 client := connect(t) 54 55 port, url, err := client.StartJupyterServer(context.Background()) 56 if err != nil { 57 t.Fatalf("expected %v, got %v", nil, err) 58 } 59 if port != grpctest.JupyterPort { 60 t.Fatalf("expected %d, got %d", grpctest.JupyterPort, port) 61 } 62 if url != grpctest.JupyterServerUrl { 63 t.Fatalf("expected %s, got %s", grpctest.JupyterServerUrl, url) 64 } 65 } 66 67 // Test that the gRPC client returns an error when the JupyterLab server fails to start 68 func TestStartJupyterServerFailure(t *testing.T) { 69 startServer(t) 70 client := connect(t) 71 grpctest.JupyterMessage = "error message" 72 grpctest.JupyterResult = false 73 errorMessage := fmt.Sprintf("failed to start JupyterLab: %s", grpctest.JupyterMessage) 74 port, url, err := client.StartJupyterServer(context.Background()) 75 if err.Error() != errorMessage { 76 t.Fatalf("expected %v, got %v", errorMessage, err) 77 } 78 if port != 0 { 79 t.Fatalf("expected %d, got %d", 0, port) 80 } 81 if url != "" { 82 t.Fatalf("expected %s, got %s", "", url) 83 } 84 }