grpcApi_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. apiv1 "github.com/OliveTin/OliveTin/gen/grpc/olivetin/api/v1"
  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 initServer(cfg *config.Config) *executor.Executor {
  18. ex := executor.DefaultExecutor(cfg)
  19. lis = bufconn.Listen(bufSize)
  20. s := grpc.NewServer()
  21. apiv1.RegisterOliveTinApiServiceServer(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. return ex
  28. }
  29. func bufDialer(context.Context, string) (net.Conn, error) {
  30. return lis.Dial()
  31. }
  32. func getNewTestServerAndClient(t *testing.T, injectedConfig *config.Config) (*grpc.ClientConn, apiv1.OliveTinApiServiceClient) {
  33. cfg = injectedConfig
  34. ctx := context.Background()
  35. conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
  36. if err != nil {
  37. t.Fatalf("Failed to dial bufnet: %v", err)
  38. }
  39. client := apiv1.NewOliveTinApiServiceClient(conn)
  40. return conn, client
  41. }
  42. func TestGetActionsAndStart(t *testing.T) {
  43. cfg = config.DefaultConfig()
  44. ex := initServer(cfg)
  45. btn1 := &config.Action{}
  46. btn1.Title = "blat"
  47. btn1.ID = "blat"
  48. btn1.Shell = "echo 'test'"
  49. cfg.Actions = append(cfg.Actions, btn1)
  50. ex.RebuildActionMap()
  51. conn, client := getNewTestServerAndClient(t, cfg)
  52. respGb, err := client.GetDashboardComponents(context.Background(), &apiv1.GetDashboardComponentsRequest{})
  53. if err != nil {
  54. t.Errorf("GetDashboardComponentsRequest: %v", err)
  55. }
  56. assert.Equal(t, true, true, "sayHello Failed")
  57. assert.Equal(t, 1, len(respGb.Actions), "Got 1 action button back")
  58. log.Printf("Response: %+v", respGb)
  59. respSa, err := client.StartAction(context.Background(), &apiv1.StartActionRequest{ActionId: "blat"})
  60. assert.Nil(t, err, "Empty err after start action")
  61. assert.NotNil(t, respSa, "Empty err after start action")
  62. defer conn.Close()
  63. }