proxy_test.go

65 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
package router

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestProxy_AddsAndRemoves(t *testing.T) {
	Proxy("app.example.com", "localhost:5000")
	defer RemoveProxy("app.example.com")

	p := Proxies()
	if p["app.example.com"] != "localhost:5000" {
		t.Errorf("expected localhost:5000, got %q", p["app.example.com"])
	}

	RemoveProxy("app.example.com")
	p = Proxies()
	if _, ok := p["app.example.com"]; ok {
		t.Error("expected proxy to be removed")
	}
}

func TestProxy_CaseInsensitive(t *testing.T) {
	Proxy("APP.Example.COM", "backend:3000")
	defer RemoveProxy("app.example.com")

	p := Proxies()
	if p["app.example.com"] != "backend:3000" {
		t.Errorf("expected case-insensitive storage, got %v", p)
	}
}

func TestProxies_ReturnsCopy(t *testing.T) {
	Proxy("test.example.com", "backend:4000")
	defer RemoveProxy("test.example.com")

	p := Proxies()
	p["test.example.com"] = "modified"

	p2 := Proxies()
	if p2["test.example.com"] != "backend:4000" {
		t.Error("Proxies() should return a copy, not a reference")
	}
}

func TestHandler_FallsThrough(t *testing.T) {
	fallback := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("fallback"))
	})

	h := Handler(fallback)
	rec := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "http://unknown.example.com/", nil)
	h.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Errorf("expected 200, got %d", rec.Code)
	}
	if rec.Body.String() != "fallback" {
		t.Errorf("expected fallback body, got %q", rec.Body.String())
	}
}