servauth_test.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package servauth_test
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. . "github.com/onsi/ginkgo"
  9. . "github.com/onsi/gomega"
  10. "github.com/vladimirok5959/golang-utils/utils/http/servauth"
  11. )
  12. var _ = Describe("servauth", func() {
  13. Context("BasicAuth", func() {
  14. var srv *httptest.Server
  15. var client *http.Client
  16. var getTestHandler = func() http.HandlerFunc {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. if _, err := w.Write([]byte("Index")); err != nil {
  19. fmt.Printf("%s\n", err.Error())
  20. }
  21. })
  22. }
  23. BeforeEach(func() {
  24. srv = httptest.NewServer(servauth.BasicAuth(getTestHandler(), "user", "pass", "msg"))
  25. client = srv.Client()
  26. })
  27. AfterEach(func() {
  28. srv.Close()
  29. })
  30. It("request credentials", func() {
  31. resp, err := client.Get(srv.URL + "/")
  32. Expect(err).To(Succeed())
  33. defer resp.Body.Close()
  34. Expect(resp.StatusCode).To(Equal(http.StatusUnauthorized))
  35. Expect(resp.Header["Www-Authenticate"]).To(Equal([]string{`Basic realm="msg"`}))
  36. body, err := io.ReadAll(resp.Body)
  37. Expect(err).To(Succeed())
  38. Expect(string(body)).To(Equal("Unauthorised\n"))
  39. })
  40. It("show with correct credentials", func() {
  41. req, err := http.NewRequest("GET", srv.URL+"/", nil)
  42. Expect(err).To(Succeed())
  43. req.SetBasicAuth("user", "pass")
  44. resp, err := client.Do(req)
  45. Expect(err).To(Succeed())
  46. defer resp.Body.Close()
  47. Expect(resp.StatusCode).To(Equal(http.StatusOK))
  48. body, err := io.ReadAll(resp.Body)
  49. Expect(err).To(Succeed())
  50. Expect(string(body)).To(Equal("Index"))
  51. })
  52. })
  53. })
  54. func TestSuite(t *testing.T) {
  55. RegisterFailHandler(Fail)
  56. RunSpecs(t, "servauth")
  57. }