Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1cb650a

Browse files
committed
Test options requests
1 parent da1298a commit 1cb650a

File tree

1 file changed

+17
-4
lines changed

1 file changed

+17
-4
lines changed

coderd/httpmw/cors_test.go

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@ func TestWorkspaceAppCors(t *testing.T) {
2424
Username: "user",
2525
}
2626

27-
handler := httpmw.WorkspaceAppCors(regex, app)
27+
handler := httpmw.WorkspaceAppCors(regex, app)(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
28+
rw.WriteHeader(http.StatusNoContent)
29+
}))
2830
methods := []string{
2931
http.MethodOptions,
3032
http.MethodHead,
@@ -72,15 +74,26 @@ func TestWorkspaceAppCors(t *testing.T) {
7274
r.Header.Set("Origin", test.origin)
7375
rw := httptest.NewRecorder()
7476

75-
handler(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
76-
rw.WriteHeader(http.StatusOK)
77-
})).ServeHTTP(rw, r)
77+
// Preflight requests need to know what method will be requested.
78+
if method == http.MethodOptions {
79+
r.Header.Set("Access-Control-Request-Method", method)
80+
}
81+
82+
handler.ServeHTTP(rw, r)
7883

7984
if test.allowed {
8085
require.Equal(t, test.origin, rw.Header().Get("Access-Control-Allow-Origin"))
8186
} else {
8287
require.Equal(t, "", rw.Header().Get("Access-Control-Allow-Origin"))
8388
}
89+
90+
// For options we should never get to our handler as the middleware
91+
// short-circuits with a 200.
92+
if method == http.MethodOptions {
93+
require.Equal(t, http.StatusOK, rw.Code)
94+
} else {
95+
require.Equal(t, http.StatusNoContent, rw.Code)
96+
}
8497
}
8598
})
8699
}

0 commit comments

Comments
 (0)