You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

63 lines
1.6 KiB

  1. package handlers
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. )
  8. func TestUnauth(t *testing.T) {
  9. h := BasicAuthHandler(StaticFileHandler("./testdata/script.js"), func(u, pwd string) (interface{}, bool) {
  10. if u == "me" && pwd == "you" {
  11. return u, true
  12. }
  13. return nil, false
  14. }, "foo")
  15. s := httptest.NewServer(h)
  16. defer s.Close()
  17. res, err := http.Get(s.URL)
  18. if err != nil {
  19. panic(err)
  20. }
  21. assertStatus(http.StatusUnauthorized, res.StatusCode, t)
  22. assertHeader("Www-Authenticate", `Basic realm="foo"`, res, t)
  23. }
  24. func TestGzippedAuth(t *testing.T) {
  25. h := GZIPHandler(BasicAuthHandler(http.HandlerFunc(
  26. func(w http.ResponseWriter, r *http.Request) {
  27. usr, ok := GetUser(w)
  28. if assertTrue(ok, "expected authenticated user, got false", t) {
  29. assertTrue(usr.(string) == "meyou", fmt.Sprintf("expected user data to be 'meyou', got '%s'", usr), t)
  30. }
  31. usr, ok = GetUserName(w)
  32. if assertTrue(ok, "expected authenticated user name, got false", t) {
  33. assertTrue(usr == "me", fmt.Sprintf("expected user name to be 'me', got '%s'", usr), t)
  34. }
  35. w.Header().Set("Content-Type", "text/plain")
  36. w.Write([]byte(usr.(string)))
  37. }), func(u, pwd string) (interface{}, bool) {
  38. if u == "me" && pwd == "you" {
  39. return u + pwd, true
  40. }
  41. return nil, false
  42. }, ""), nil)
  43. s := httptest.NewServer(h)
  44. defer s.Close()
  45. req, err := http.NewRequest("GET", "http://me:you@"+s.URL[7:], nil)
  46. if err != nil {
  47. panic(err)
  48. }
  49. req.Header.Set("Accept-Encoding", "gzip")
  50. res, err := http.DefaultClient.Do(req)
  51. if err != nil {
  52. panic(err)
  53. }
  54. assertStatus(http.StatusOK, res.StatusCode, t)
  55. assertGzippedBody([]byte("me"), res, t)
  56. }