headers_test.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package rest
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. )
  7. func TestIsAuthenticated(t *testing.T) {
  8. type TestCase struct {
  9. Req *http.Request
  10. Token string
  11. Expected bool
  12. }
  13. testCases := []TestCase{}
  14. req := httptest.NewRequest("GET", "/", nil)
  15. req.Header.Add("authorization", "bearer abcd")
  16. testCases = append(testCases, TestCase{Req: req, Token: "abcd", Expected: true})
  17. req = httptest.NewRequest("POST", "/", nil)
  18. req.Header.Add("authorization", "Bearer defg hijk")
  19. testCases = append(testCases, TestCase{Req: req, Token: "defg hijk", Expected: true})
  20. req = httptest.NewRequest("DELETE", "/", nil)
  21. testCases = append(testCases, TestCase{Req: req, Token: "", Expected: true})
  22. req = httptest.NewRequest("GET", "/", nil)
  23. testCases = append(testCases, TestCase{Req: req, Token: "lmno"})
  24. req = httptest.NewRequest("GET", "/", nil)
  25. req.Header.Add("authorization", "Bearer pqrs")
  26. testCases = append(testCases, TestCase{Req: req, Expected: true})
  27. for i, tc := range testCases {
  28. t.Logf("(%d) Testing request authorization header against %q", i, tc.Token)
  29. actual := IsAuthenticated(tc.Req, tc.Token)
  30. if actual != tc.Expected {
  31. t.Errorf("Expected %v, got %v", tc.Expected, actual)
  32. }
  33. }
  34. }
  35. func TestReadBearerToken(t *testing.T) {
  36. type TestCase struct {
  37. Req *http.Request
  38. Expected string
  39. }
  40. testCases := []TestCase{}
  41. req := httptest.NewRequest("GET", "/", nil)
  42. req.Header.Add("authorization", "bearer abcd")
  43. testCases = append(testCases, TestCase{Req: req, Expected: "abcd"})
  44. req = httptest.NewRequest("POST", "/", nil)
  45. req.Header.Add("authorization", "Bearer defg hijk")
  46. testCases = append(testCases, TestCase{Req: req, Expected: "defg hijk"})
  47. req = httptest.NewRequest("DELETE", "/", nil)
  48. testCases = append(testCases, TestCase{Req: req, Expected: ""})
  49. for i, tc := range testCases {
  50. t.Logf("(%d) Testing request authorization header against %q", i, tc.Expected)
  51. actual := ReadBearerToken(tc.Req)
  52. if actual != tc.Expected {
  53. t.Errorf("Expected %q, got %q", tc.Expected, actual)
  54. }
  55. }
  56. }