package main import ( "net/http" "net/http/httptest" "strings" "testing" ) func TestHandleCaesarAllowed(t *testing.T) { allowAll := func(r *http.Request) bool { return true } bodyReader := strings.NewReader("hello world") req := httptest.NewRequest("POST", "/", bodyReader) resp := httptest.NewRecorder() handler := handleCaesar(allowAll) handler(resp, req) if resp.Code != http.StatusOK { t.Errorf("expected OK status %d but got %d", http.StatusOK, resp.Code) } body := string(resp.Body.Bytes()) if body != "khoor zruog" { t.Errorf("got unexpected body %s", body) } } func TestCaesarNotAllowed(t *testing.T) { denyAll := func(r *http.Request) bool { return false } req := httptest.NewRequest("POST", "/", nil) resp := httptest.NewRecorder() handler := handleCaesar(denyAll) handler(resp, req) if resp.Code != http.StatusUnauthorized { t.Errorf("should not have been authorized") } if len(resp.Body.Bytes()) != 0 { t.Errorf("should not have gotten a response body") } } func TestCaesarBadRequest(t *testing.T) { allowAll := func(r *http.Request) bool { return true } req := httptest.NewRequest("GET", "/", nil) resp := httptest.NewRecorder() handler := handleCaesar(allowAll) handler(resp, req) if resp.Code != http.StatusBadRequest { t.Errorf("status should have been bad request, got %d", resp.Code) } if len(resp.Body.Bytes()) != 0 { t.Errorf("should not have gotten a response body") } }