github.com/yandex/pandora@v0.5.32/components/providers/http/middleware/headerdate/middleware_test.go (about) 1 package headerdate 2 3 import ( 4 "context" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 "time" 9 10 "github.com/stretchr/testify/assert" 11 "go.uber.org/zap" 12 ) 13 14 func TestMiddleware_InitMiddleware(t *testing.T) { 15 cfg := Config{Location: ""} 16 middleware, err := NewMiddleware(cfg) 17 assert.NoError(t, err) 18 19 err = middleware.InitMiddleware(context.Background(), zap.NewNop()) 20 assert.NoError(t, err) 21 } 22 23 func TestMiddleware_UpdateRequest(t *testing.T) { 24 t.Run("empty config", func(t *testing.T) { 25 cfg := Config{} 26 middleware, err := NewMiddleware(cfg) 27 assert.NoError(t, err) 28 29 req := httptest.NewRequest(http.MethodGet, "/", nil) 30 31 err = middleware.UpdateRequest(req) 32 assert.NoError(t, err) 33 34 dateHeader := req.Header.Get("Date") 35 assert.NotEmpty(t, dateHeader) 36 37 expectedDate := time.Now().In(time.UTC).Format(http.TimeFormat) 38 assert.Equal(t, expectedDate, dateHeader) 39 }) 40 t.Run("America/New_York", func(t *testing.T) { 41 loc, err := time.LoadLocation("America/New_York") 42 assert.NoError(t, err) 43 44 cfg := Config{Location: "America/New_York"} 45 middleware, err := NewMiddleware(cfg) 46 assert.NoError(t, err) 47 48 req := httptest.NewRequest(http.MethodGet, "/", nil) 49 50 err = middleware.UpdateRequest(req) 51 assert.NoError(t, err) 52 53 dateHeader := req.Header.Get("Date") 54 assert.NotEmpty(t, dateHeader) 55 56 expectedDate := time.Now().In(loc).Format(http.TimeFormat) 57 assert.Equal(t, expectedDate, dateHeader) 58 }) 59 t.Run("custom header name", func(t *testing.T) { 60 loc, err := time.LoadLocation("America/New_York") 61 assert.NoError(t, err) 62 63 cfg := Config{Location: "America/New_York", HeaderName: "CreatedDate"} 64 middleware, err := NewMiddleware(cfg) 65 assert.NoError(t, err) 66 67 req := httptest.NewRequest(http.MethodGet, "/", nil) 68 69 err = middleware.UpdateRequest(req) 70 assert.NoError(t, err) 71 72 dateHeader := req.Header.Get("CreatedDate") 73 assert.NotEmpty(t, dateHeader) 74 75 expectedDate := time.Now().In(loc).Format(http.TimeFormat) 76 assert.Equal(t, expectedDate, dateHeader) 77 }) 78 } 79 80 func TestMiddleware_UpdateRequest_InvalidLocation(t *testing.T) { 81 cfg := Config{Location: "Invalid/Location"} 82 _, err := NewMiddleware(cfg) 83 assert.Error(t, err) 84 }