github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/web/middlewares/cors_test.go (about)

     1  package middlewares
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httptest"
     6  	"testing"
     7  
     8  	"github.com/cozy/cozy-stack/pkg/assets/dynamic"
     9  	"github.com/cozy/cozy-stack/pkg/config/config"
    10  	"github.com/cozy/cozy-stack/tests/testutils"
    11  	"github.com/labstack/echo/v4"
    12  	"github.com/stretchr/testify/assert"
    13  	"github.com/stretchr/testify/require"
    14  )
    15  
    16  func TestCors(t *testing.T) {
    17  	if testing.Short() {
    18  		t.Skip("an instance is required for this test: test skipped due to the use of --short flag")
    19  	}
    20  
    21  	config.UseTestFile(t)
    22  	config.GetConfig().Assets = "../../assets"
    23  	setup := testutils.NewSetup(t, t.Name())
    24  
    25  	setup.SetupSwiftTest()
    26  	require.NoError(t, dynamic.InitDynamicAssetFS(config.FsURL().String()), "Could not init dynamic FS")
    27  
    28  	t.Run("CORSMiddleware", func(t *testing.T) {
    29  		e := echo.New()
    30  		req, _ := http.NewRequest(echo.OPTIONS, "http://cozy.local/data/io.cozy.files", nil)
    31  		req.Header.Set("Origin", "fakecozy.local")
    32  		rec := httptest.NewRecorder()
    33  		c := e.NewContext(req, rec)
    34  		h := CORS(CORSOptions{})(echo.NotFoundHandler)
    35  		_ = h(c)
    36  		assert.Equal(t, "fakecozy.local", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
    37  	})
    38  
    39  	t.Run("CORSMiddlewareNotAuth", func(t *testing.T) {
    40  		e := echo.New()
    41  		req, _ := http.NewRequest(echo.OPTIONS, "http://cozy.local/auth/register", nil)
    42  		req.Header.Set("Origin", "fakecozy.local")
    43  		rec := httptest.NewRecorder()
    44  		c := e.NewContext(req, rec)
    45  		c.SetPath(req.URL.Path)
    46  		h := CORS(CORSOptions{BlockList: []string{"/auth/"}})(echo.NotFoundHandler)
    47  		_ = h(c)
    48  		assert.Equal(t, "", rec.Header().Get(echo.HeaderAccessControlAllowOrigin))
    49  	})
    50  }