|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/httptest" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/assert" |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | +) |
| 11 | + |
| 12 | +func TestCorsHeadersWithConfig_Enabled(t *testing.T) { |
| 13 | + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 14 | + w.WriteHeader(http.StatusOK) |
| 15 | + _, err := w.Write([]byte("test response")) |
| 16 | + require.NoError(t, err) |
| 17 | + }) |
| 18 | + |
| 19 | + corsHandler := CorsHeadersWithConfig(true, "*")(handler) |
| 20 | + |
| 21 | + // Test GET request |
| 22 | + req := httptest.NewRequest("GET", "/dev/projects", nil) |
| 23 | + w := httptest.NewRecorder() |
| 24 | + corsHandler.ServeHTTP(w, req) |
| 25 | + |
| 26 | + assert.Equal(t, "*", w.Header().Get("Access-Control-Allow-Origin")) |
| 27 | + assert.Equal(t, "GET,POST,PUT,PATCH,DELETE,OPTIONS", w.Header().Get("Access-Control-Allow-Methods")) |
| 28 | + assert.Equal(t, http.StatusOK, w.Code) |
| 29 | +} |
| 30 | + |
| 31 | +func TestCorsHeadersWithConfig_OptionsRequest(t *testing.T) { |
| 32 | + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 33 | + t.Error("Handler should not be called for OPTIONS request") |
| 34 | + }) |
| 35 | + |
| 36 | + corsHandler := CorsHeadersWithConfig(true, "https://example.com")(handler) |
| 37 | + |
| 38 | + // Test OPTIONS preflight request |
| 39 | + req := httptest.NewRequest("OPTIONS", "/dev/projects", nil) |
| 40 | + w := httptest.NewRecorder() |
| 41 | + corsHandler.ServeHTTP(w, req) |
| 42 | + |
| 43 | + assert.Equal(t, "https://example.com", w.Header().Get("Access-Control-Allow-Origin")) |
| 44 | + assert.Equal(t, http.StatusOK, w.Code) |
| 45 | +} |
| 46 | + |
| 47 | +func TestCorsHeadersWithConfig_Disabled(t *testing.T) { |
| 48 | + handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 49 | + w.WriteHeader(http.StatusOK) |
| 50 | + _, err := w.Write([]byte("test response")) |
| 51 | + require.NoError(t, err) |
| 52 | + }) |
| 53 | + |
| 54 | + corsHandler := CorsHeadersWithConfig(false, "*")(handler) |
| 55 | + |
| 56 | + // Test GET request with CORS disabled |
| 57 | + req := httptest.NewRequest("GET", "/dev/projects", nil) |
| 58 | + w := httptest.NewRecorder() |
| 59 | + corsHandler.ServeHTTP(w, req) |
| 60 | + |
| 61 | + assert.Empty(t, w.Header().Get("Access-Control-Allow-Origin"), "Expected no CORS headers when disabled") |
| 62 | + assert.Equal(t, http.StatusOK, w.Code) |
| 63 | +} |
0 commit comments