summaryrefslogtreecommitdiff
path: root/server/main_test.go
blob: 75ddcdb6b792d041955bcdda845f08d146eec75a (plain)
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
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")
	}
}