MCPcopy
hub / github.com/labstack/echo / TestRateLimiterWithConfig

Function TestRateLimiterWithConfig

middleware/rate_limiter_test.go:74–127  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

72}
73
74func TestRateLimiterWithConfig(t *testing.T) {
75 var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3})
76
77 e := echo.New()
78
79 handler := func(c *echo.Context) error {
80 return c.String(http.StatusOK, "test")
81 }
82
83 mw, err := RateLimiterConfig{
84 IdentifierExtractor: func(c *echo.Context) (string, error) {
85 id := c.Request().Header.Get(echo.HeaderXRealIP)
86 if id == "" {
87 return "", errors.New("invalid identifier")
88 }
89 return id, nil
90 },
91 DenyHandler: func(ctx *echo.Context, identifier string, err error) error {
92 return ctx.JSON(http.StatusForbidden, nil)
93 },
94 ErrorHandler: func(ctx *echo.Context, err error) error {
95 return ctx.JSON(http.StatusBadRequest, nil)
96 },
97 Store: inMemoryStore,
98 }.ToMiddleware()
99 assert.NoError(t, err)
100
101 testCases := []struct {
102 id string
103 code int
104 }{
105 {"127.0.0.1", http.StatusOK},
106 {"127.0.0.1", http.StatusOK},
107 {"127.0.0.1", http.StatusOK},
108 {"127.0.0.1", http.StatusForbidden},
109 {"", http.StatusBadRequest},
110 {"127.0.0.1", http.StatusForbidden},
111 {"127.0.0.1", http.StatusForbidden},
112 }
113
114 for _, tc := range testCases {
115 req := httptest.NewRequest(http.MethodGet, "/", nil)
116 req.Header.Add(echo.HeaderXRealIP, tc.id)
117
118 rec := httptest.NewRecorder()
119
120 c := e.NewContext(req, rec)
121
122 err := mw(handler)(c)
123
124 assert.NoError(t, err)
125 assert.Equal(t, tc.code, rec.Code)
126 }
127}
128
129func TestRateLimiterWithConfig_defaultDenyHandler(t *testing.T) {
130 var inMemoryStore = NewRateLimiterMemoryStoreWithConfig(RateLimiterMemoryStoreConfig{Rate: 1, Burst: 3})

Callers

nothing calls this directly

Calls 8

StringMethod · 0.95
RequestMethod · 0.95
JSONMethod · 0.80
NewContextMethod · 0.80
ToMiddlewareMethod · 0.65
AddMethod · 0.65
GetMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…