api_test.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package api
  2. import (
  3. "context"
  4. "testing"
  5. "connectrpc.com/connect"
  6. "github.com/stretchr/testify/assert"
  7. log "github.com/sirupsen/logrus"
  8. apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
  9. apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
  10. config "github.com/OliveTin/OliveTin/internal/config"
  11. "github.com/OliveTin/OliveTin/internal/executor"
  12. "net/http"
  13. "net/http/httptest"
  14. "path"
  15. )
  16. func getNewTestServerAndClient(t *testing.T, injectedConfig *config.Config) (*httptest.Server, apiv1connect.OliveTinApiServiceClient) {
  17. ex := executor.DefaultExecutor(injectedConfig)
  18. ex.RebuildActionMap()
  19. apiPath, apiHandler := GetNewHandler(ex)
  20. mux := http.NewServeMux()
  21. mux.Handle("/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  22. log.Infof("HTTP Request: %s %s", r.Method, r.URL.Path)
  23. // Translate /api/<service>/<method> to <service>/<method>
  24. fn := path.Base(r.URL.Path)
  25. r.URL.Path = apiPath + fn
  26. apiHandler.ServeHTTP(w, r)
  27. }))
  28. log.Infof("API path is %s", apiPath)
  29. httpclient := &http.Client{}
  30. ts := httptest.NewServer(mux)
  31. client := apiv1connect.NewOliveTinApiServiceClient(httpclient, ts.URL+"/api")
  32. log.Infof("Test server URL is %s", ts.URL+"/api"+apiPath)
  33. return ts, client
  34. }
  35. func TestGetActionsAndStart(t *testing.T) {
  36. cfg := config.DefaultConfig()
  37. btn1 := &config.Action{}
  38. btn1.Title = "blat"
  39. btn1.ID = "blat"
  40. btn1.Shell = "echo 'test'"
  41. cfg.Actions = append(cfg.Actions, btn1)
  42. ex := executor.DefaultExecutor(cfg)
  43. ex.RebuildActionMap()
  44. conn, client := getNewTestServerAndClient(t, cfg)
  45. respInit, errInit := client.Init(context.Background(), connect.NewRequest(&apiv1.InitRequest{}))
  46. respGetReady, errReady := client.GetReadyz(context.Background(), connect.NewRequest(&apiv1.GetReadyzRequest{}))
  47. if errInit != nil {
  48. t.Errorf("Init request failed: %v", errInit)
  49. return
  50. }
  51. if errReady != nil {
  52. t.Errorf("GetReadyz request failed: %v", errReady)
  53. return
  54. }
  55. log.Infof("GetReadyz response: %v", respGetReady.Msg)
  56. assert.Equal(t, true, true, "sayHello Failed")
  57. // assert.Equal(t, 1, len(respGb.Msg.Actions), "Got 1 action button back")
  58. log.Printf("Response: %+v", respInit)
  59. respSa, err := client.StartAction(context.Background(), connect.NewRequest(&apiv1.StartActionRequest{
  60. // ActionId: "blat"
  61. }))
  62. assert.NotNil(t, err, "Error 404 after start action")
  63. assert.Nil(t, respSa, "Nil response for non existing action")
  64. defer conn.Close()
  65. }