api_test.go 2.1 KB

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