grpcApi_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package grpcapi
  2. // Thank you: https://stackoverflow.com/questions/42102496/testing-a-grpc-service
  3. import (
  4. "context"
  5. "github.com/stretchr/testify/assert"
  6. "google.golang.org/grpc"
  7. "google.golang.org/grpc/test/bufconn"
  8. "net"
  9. "testing"
  10. log "github.com/sirupsen/logrus"
  11. pb "github.com/OliveTin/OliveTin/gen/grpc"
  12. config "github.com/OliveTin/OliveTin/internal/config"
  13. "github.com/OliveTin/OliveTin/internal/executor"
  14. )
  15. const bufSize = 1024 * 1024
  16. var lis *bufconn.Listener
  17. func init() {
  18. ex := executor.DefaultExecutor()
  19. lis = bufconn.Listen(bufSize)
  20. s := grpc.NewServer()
  21. pb.RegisterOliveTinApiServer(s, newServer(ex))
  22. go func() {
  23. if err := s.Serve(lis); err != nil {
  24. log.Fatalf("Server exited with error: %v", err)
  25. }
  26. }()
  27. }
  28. func bufDialer(context.Context, string) (net.Conn, error) {
  29. return lis.Dial()
  30. }
  31. func getNewTestServerAndClient(t *testing.T, injectedConfig *config.Config) (*grpc.ClientConn, pb.OliveTinApiClient) {
  32. cfg = injectedConfig
  33. ctx := context.Background()
  34. conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
  35. if err != nil {
  36. t.Fatalf("Failed to dial bufnet: %v", err)
  37. }
  38. client := pb.NewOliveTinApiClient(conn)
  39. return conn, client
  40. }
  41. func TestGetActionsAndStart(t *testing.T) {
  42. cfg = config.DefaultConfig()
  43. btn1 := config.Action{}
  44. btn1.Title = "blat"
  45. btn1.Shell = "echo 'test'"
  46. cfg.Actions = append(cfg.Actions, btn1)
  47. conn, client := getNewTestServerAndClient(t, cfg)
  48. respGb, err := client.GetDashboardComponents(context.Background(), &pb.GetDashboardComponentsRequest{})
  49. if err != nil {
  50. t.Errorf("GetDashboardComponentsRequest: %v", err)
  51. }
  52. assert.Equal(t, true, true, "sayHello Failed")
  53. assert.Equal(t, 1, len(respGb.Actions), "Got 1 action button back")
  54. log.Printf("Response: %+v", respGb)
  55. respSa, err := client.StartAction(context.Background(), &pb.StartActionRequest{ActionName: "blat"})
  56. assert.Nil(t, err, "Empty err after start action")
  57. assert.NotNil(t, respSa, "Empty err after start action")
  58. defer conn.Close()
  59. }