package client import ( "io/ioutil" "net/http" "net/http/httptest" "strings" "testing" ) func TestBadAuth(t *testing.T) { var hf http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("authorization") != "token TEST-TOKEN" { w.WriteHeader(http.StatusUnauthorized) return } w.Write([]byte("encoded yay")) } tests := []struct { name string tok string expectErr bool expectBody bool }{ {"valid token", "TEST-TOKEN", false, true}, {"empty token", "", true, false}, {"invalid token", "bad token", true, false}, } server := httptest.NewServer(hf) defer server.Close() c := CaesarClient{Endpoint: server.URL} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.EncodeMessage(strings.NewReader("secret message")) if err == nil { t.Errorf("should have gotten error") } if r != nil { t.Errorf("should not have gotten a reader") } }) } } func TestEncode(t *testing.T) { var hf http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("response")) } server := httptest.NewServer(hf) defer server.Close() c := CaesarClient{Endpoint: server.URL} // HL r, err := c.EncodeMessage(strings.NewReader("secret message")) if err != nil { t.Errorf("should not have gotten error: %v", err) } if r == nil { t.Errorf("should have gotten a reader") } resp, err := ioutil.ReadAll(r) if err != nil { t.Fatalf("could not read message: %v", err) } if string(resp) != "response" { t.Errorf("expected 'response' but got '%s'", resp) } } func TestUserAgent(t *testing.T) { var ua string var hf http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) { ua = r.Header.Get("user-agent") } server := httptest.NewServer(hf) defer server.Close() c := CaesarClient{Endpoint: server.URL} c.EncodeMessage(strings.NewReader("secret message")) expected := "caesar-client/1.0" if ua != expected { t.Errorf("expected user agent header %q but got %q", expected, ua) } }