serve_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package web
  2. import (
  3. "encoding/json"
  4. "io"
  5. "log"
  6. "net/http"
  7. "net/http/httptest"
  8. "path/filepath"
  9. "testing"
  10. "github.com/gorilla/mux"
  11. "golang.org/x/exp/slices"
  12. "code.osinet.fr/fgm/lbc/domain"
  13. )
  14. func TestServer_Serve(t *testing.T) {
  15. logger := &log.Logger{}
  16. logger.SetOutput(io.Discard)
  17. const base = "/test"
  18. happyPath := filepath.Join(base, "2", "3", "7", domain.Fizz, domain.Buzz)
  19. expectedHappy := []string{
  20. "1",
  21. domain.Fizz,
  22. domain.Buzz,
  23. domain.Fizz,
  24. "5",
  25. domain.Both,
  26. "7",
  27. }
  28. tests := [...]struct {
  29. name string
  30. headers http.Header
  31. path string
  32. expCode int
  33. expected []string
  34. }{
  35. {"happy explicit", http.Header{"Accept": []string{JSON}}, happyPath, http.StatusOK, expectedHappy},
  36. {"happy wild", http.Header{"Accept": []string{"*/*"}}, happyPath, http.StatusOK, expectedHappy},
  37. {"sad accept", http.Header{"Accept": []string{"text/html"}}, happyPath, http.StatusNotAcceptable, nil},
  38. {"sad charset", http.Header{"Accept-Charset": []string{"iso-8859-15"}}, happyPath, http.StatusNotAcceptable, nil},
  39. {"bad route params", nil, filepath.Join(base, "2", "3", "0", domain.Fizz, domain.Buzz), http.StatusNotFound, nil},
  40. {"bad domain params", nil, filepath.Join(base, "2", "3", "2", domain.Fizz, domain.Buzz), http.StatusInternalServerError, nil},
  41. }
  42. for _, test := range tests {
  43. t.Run(test.name, func(t *testing.T) {
  44. req, err := http.NewRequest("GET", test.path, nil)
  45. if err != nil {
  46. t.Fatal(err)
  47. }
  48. req.Header = test.headers
  49. rec := httptest.NewRecorder()
  50. // We need a router to inject variables from path, preventing us from a straight handler.ServerHTTP(rec, req)
  51. router := mux.NewRouter()
  52. router.HandleFunc(base+PathFB, MakeFizzBuzz(logger, true))
  53. router.ServeHTTP(rec, req)
  54. status := rec.Code
  55. if status != test.expCode {
  56. t.Fatalf("handler returned %d, but expected %d", status, test.expCode)
  57. }
  58. if status >= http.StatusMultipleChoices {
  59. return
  60. }
  61. actual := make([]string, 0, len(test.expected))
  62. err = json.Unmarshal(rec.Body.Bytes(), &actual)
  63. if err != nil {
  64. t.Fatal(err)
  65. }
  66. if !slices.Equal(actual, test.expected) {
  67. t.Errorf("handler returned:\n%#v\nbut expected:\n%#v\n", actual, test.expected)
  68. }
  69. })
  70. }
  71. }