routes_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package server
  2. import (
  3. "context"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. func setupServer(t *testing.T) (*Server, error) {
  11. t.Helper()
  12. return NewServer()
  13. }
  14. func Test_Routes(t *testing.T) {
  15. type testCase struct {
  16. Name string
  17. Method string
  18. Path string
  19. Setup func(t *testing.T, req *http.Request)
  20. Expected func(t *testing.T, resp *http.Response)
  21. }
  22. testCases := []testCase{
  23. {
  24. Name: "Version Handler",
  25. Method: http.MethodGet,
  26. Path: "/api/version",
  27. Setup: func(t *testing.T, req *http.Request) {
  28. },
  29. Expected: func(t *testing.T, resp *http.Response) {
  30. contentType := resp.Header.Get("Content-Type")
  31. assert.Equal(t, contentType, "application/json; charset=utf-8")
  32. body, err := io.ReadAll(resp.Body)
  33. assert.Nil(t, err)
  34. assert.Equal(t, `{"version":"0.0.0"}`, string(body))
  35. },
  36. },
  37. }
  38. s, err := setupServer(t)
  39. assert.Nil(t, err)
  40. router := s.GenerateRoutes()
  41. httpSrv := httptest.NewServer(router)
  42. t.Cleanup(httpSrv.Close)
  43. for _, tc := range testCases {
  44. u := httpSrv.URL + tc.Path
  45. req, err := http.NewRequestWithContext(context.TODO(), tc.Method, u, nil)
  46. assert.Nil(t, err)
  47. if tc.Setup != nil {
  48. tc.Setup(t, req)
  49. }
  50. resp, err := httpSrv.Client().Do(req)
  51. assert.Nil(t, err)
  52. if tc.Expected != nil {
  53. tc.Expected(t, resp)
  54. }
  55. }
  56. }