package shell import ( "net/http" "net/http/httptest" "strings" "testing" ) func postJSON(h http.Handler, target, body string) *httptest.ResponseRecorder { req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body)) req.Header.Set("Content-Type", "application/json") rec := httptest.NewRecorder() h.ServeHTTP(rec, req) return rec } func TestNotify(t *testing.T) { var got []Notification s, _ := newShell(t, Options{Notify: func(n Notification) error { got = append(got, n); return nil }}) rec := postJSON(s, notifyPath, `{"id":"!a:x","title":" Room\u0007 ","body":"Ann:\nhi","roomId":"!a:x"}`) if rec.Code != http.StatusNoContent || len(got) != 1 { t.Fatalf("notify: %d, %v", rec.Code, got) } if want := (Notification{ID: "!a:x", Title: "Room", Body: "Ann: hi", RoomID: "!a:x"}); got[0] != want { t.Errorf("got %+v, want %+v", got[0], want) } // Missing fields, the wrong method and a body that isn't JSON are refused. if rec := postJSON(s, notifyPath, `{"id":"","title":"x"}`); rec.Code != http.StatusBadRequest { t.Errorf("no id: %d", rec.Code) } if rec := do(s, http.MethodGet, notifyPath, ""); rec.Code != http.StatusMethodNotAllowed { t.Errorf("GET: %d", rec.Code) } if rec := do(s, http.MethodPost, notifyPath, `{"id":"a","title":"b"}`); rec.Code != http.StatusUnsupportedMediaType { t.Errorf("no content type: %d", rec.Code) } if len(got) != 1 { t.Errorf("refused requests notified: %v", got) } } func TestTitle(t *testing.T) { var title string s, _ := newShell(t, Options{SetTitle: func(v string) { title = v }}) if rec := postJSON(s, titlePath, `{"title":"(2) Warp"}`); rec.Code != http.StatusNoContent || title != "(2) Warp" { t.Errorf("title: %d %q", rec.Code, title) } } func TestClip(t *testing.T) { if got := clip(" abcdef ", 4); got != "abc…" { t.Errorf("clip: %q", got) } if got := clip("żółw", 4); got != "żółw" { t.Errorf("clip: %q", got) } }