Micro-service for file storage and processing written in Go
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.

50 lines
1.5 KiB

  1. package middlewares
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/bxcodec/faker/v3"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. func TestAuthenticationMiddleware(t *testing.T) {
  10. token := faker.Word()
  11. middleware := CreateAuthenticationMiddleware(token)
  12. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  13. w.WriteHeader(http.StatusOK)
  14. })
  15. middlewareHandler := middleware.Middleware(handler)
  16. t.Run("AuthenticationMiddleware returns 403 response when authorization header is incorrect", func(t *testing.T) {
  17. request, _ := http.NewRequest("GET", "/", nil)
  18. responseRecorder := httptest.NewRecorder()
  19. middlewareHandler.ServeHTTP(responseRecorder, request)
  20. assert.Equal(t, 403, responseRecorder.Code)
  21. })
  22. t.Run("AuthenticationMiddleware returns 403 response when authorization header is missing Bearer prefix", func(t *testing.T) {
  23. request, _ := http.NewRequest("GET", "/", nil)
  24. request.Header.Set("Authorization", token)
  25. responseRecorder := httptest.NewRecorder()
  26. middlewareHandler.ServeHTTP(responseRecorder, request)
  27. assert.Equal(t, 403, responseRecorder.Code)
  28. })
  29. t.Run("AuthenticationMiddleware continues when authorization header is correct", func(t *testing.T) {
  30. request, _ := http.NewRequest("GET", "/", nil)
  31. request.Header.Set("Authorization", "Bearer "+token)
  32. responseRecorder := httptest.NewRecorder()
  33. middlewareHandler.ServeHTTP(responseRecorder, request)
  34. assert.Equal(t, 200, responseRecorder.Code)
  35. })
  36. }