74 lines
2.2 KiB
Go
74 lines
2.2 KiB
Go
package studio
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
)
|
|
|
|
// The one property share.go promises: another origin can read, and cannot do anything else.
|
|
func TestCORSIsReadOnly(t *testing.T) {
|
|
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
h := readOnlyCORS(inner)
|
|
|
|
for _, tc := range []struct {
|
|
method string
|
|
want string
|
|
}{
|
|
{http.MethodGet, "*"},
|
|
{http.MethodHead, "*"},
|
|
{http.MethodPost, ""},
|
|
{http.MethodOptions, ""},
|
|
{http.MethodDelete, ""},
|
|
} {
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest(tc.method, "/api/legend", nil))
|
|
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != tc.want {
|
|
t.Errorf("%s: Access-Control-Allow-Origin = %q, want %q", tc.method, got, tc.want)
|
|
}
|
|
// No preflight is answered: a browser needs Allow-Methods to send a cross-origin POST, and it never
|
|
// gets one.
|
|
if got := rec.Header().Get("Access-Control-Allow-Methods"); got != "" {
|
|
t.Errorf("%s: Access-Control-Allow-Methods = %q, want none", tc.method, got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestServeJSONFileIsTheFileOnDisk(t *testing.T) {
|
|
dir := t.TempDir()
|
|
path := filepath.Join(dir, "legend.json")
|
|
// Commentary and formatting are the point: what Orogen reads is the text the author wrote.
|
|
text := "{\n \"_comment\": \"kept\",\n \"classes\": []\n}\n"
|
|
if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
rec := httptest.NewRecorder()
|
|
serveJSONFile(rec, path)
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("status %d", rec.Code)
|
|
}
|
|
if got := rec.Body.String(); got != text {
|
|
t.Errorf("body changed:\n%s\nwant\n%s", got, text)
|
|
}
|
|
if ct := rec.Header().Get("Content-Type"); ct != "application/json" {
|
|
t.Errorf("Content-Type %q", ct)
|
|
}
|
|
|
|
// A planet with no overlay legend has "" for its path, and that is a 404 rather than a read of "".
|
|
rec = httptest.NewRecorder()
|
|
serveJSONFile(rec, "")
|
|
if rec.Code != http.StatusNotFound {
|
|
t.Errorf("empty path: status %d, want 404", rec.Code)
|
|
}
|
|
rec = httptest.NewRecorder()
|
|
serveJSONFile(rec, filepath.Join(dir, "missing.json"))
|
|
if rec.Code != http.StatusNotFound {
|
|
t.Errorf("missing file: status %d, want 404", rec.Code)
|
|
}
|
|
}
|