Files
creator-hub/cmd/control-plane/main_test.go
T

83 lines
2.5 KiB
Go

package main
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"testing"
)
func TestAPIProxyPreservesMethodPathAndStatus(t *testing.T) {
requests := make(chan *http.Request, 1)
gateway := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
requests <- request
response.WriteHeader(http.StatusServiceUnavailable)
}))
defer gateway.Close()
upstream, err := url.Parse(gateway.URL)
if err != nil {
t.Fatal(err)
}
request := httptest.NewRequest(http.MethodPost, "/api/browsers/account-a/start?force=true", nil)
response, err := newHandler(upstream, t.TempDir()).Test(request)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
proxied := <-requests
if proxied.Method != http.MethodPost || proxied.URL.Path != "/v1/browsers/account-a/start" || proxied.URL.RawQuery != "force=true" {
t.Fatalf("unexpected proxy request %s %s", proxied.Method, proxied.URL.String())
}
if response.StatusCode != http.StatusServiceUnavailable {
t.Fatalf("expected upstream status 503, got %d", response.StatusCode)
}
}
func TestLoadConfigRejectsInvalidGateway(t *testing.T) {
t.Setenv("DOCKER_GATEWAY_URL", "file:///var/run/docker.sock")
if _, err := loadConfig(); err == nil {
t.Fatal("expected invalid gateway URL to be rejected")
}
}
func TestSPAServesFileAndIndexFallback(t *testing.T) {
directory := t.TempDir()
files := map[string]string{
"index.html": "index",
"app.js": "asset",
"hello world.js": "space",
"应用.js": "unicode",
}
for name, body := range files {
if err := os.WriteFile(filepath.Join(directory, name), []byte(body), 0o600); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(directory, "..", "outside-secret.txt"), []byte("secret"), 0o600); err != nil {
t.Fatal(err)
}
app := newHandler(&url.URL{Scheme: "http", Host: "127.0.0.1"}, directory)
for path, want := range map[string]string{
"/app.js": "asset",
"/hello%20world.js": "space",
"/%E5%BA%94%E7%94%A8.js": "unicode",
"/%2e%2e%2foutside-secret.txt": "index",
"/dashboard": "index",
} {
response, err := app.Test(httptest.NewRequest(http.MethodGet, path, nil))
if err != nil {
t.Fatal(err)
}
body, readErr := io.ReadAll(response.Body)
response.Body.Close()
if readErr != nil || response.StatusCode != http.StatusOK || string(body) != want {
t.Fatalf("GET %s: status=%d body=%q err=%v", path, response.StatusCode, body, readErr)
}
}
}