Перенесите реализацию ЛР 4 на стенд ЛР 5
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/chat"
|
||||
"messenger/internal/platform/httpx"
|
||||
)
|
||||
|
||||
func messageRouter(f fixture, actor uuid.UUID) *gin.Engine {
|
||||
r := gin.New()
|
||||
r.Use(func(c *gin.Context) { httpx.SetUserID(c, actor) })
|
||||
chat.NewHandler(f.svc).Register(r)
|
||||
return r
|
||||
}
|
||||
|
||||
func sendJSON(r http.Handler, chatID uuid.UUID, key, body string) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(http.MethodPost, "/chats/"+chatID.String()+"/messages", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestMessageAttachmentJSONEmptyArrayAndOmitted(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
c := f.newChat(t, f.alice)
|
||||
r := messageRouter(f, f.alice)
|
||||
for i, body := range []string{`{"text":"hello","attachment_ids":[]}`, `{"text":"hello"}`} {
|
||||
rec := sendJSON(r, c, fmt.Sprint(i), body)
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("send %s: %d %s", body, rec.Code, rec.Body)
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &fields); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(fields["attachment_ids"]) != "[]" {
|
||||
t.Fatalf("attachment_ids = %s, want []", fields["attachment_ids"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentJSONRejectsInvalidArrays(t *testing.T) {
|
||||
f := newFixture(t)
|
||||
c := f.newChat(t, f.alice)
|
||||
r := messageRouter(f, f.alice)
|
||||
id := uuid.NewString()
|
||||
for _, raw := range []string{
|
||||
"null", `"not an array"`, "{}", "1", "[null]", "[1]", `["bad"]`,
|
||||
`["00000000-0000-0000-0000-000000000000"]`,
|
||||
fmt.Sprintf("[%q]", strings.ReplaceAll(id, "-", "")),
|
||||
fmt.Sprintf("[%q,%q]", id, strings.ToUpper(id)),
|
||||
"[" + strings.TrimSuffix(strings.Repeat(fmt.Sprintf("%q,", id), 11), ",") + "]",
|
||||
} {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
rec := sendJSON(r, c, "invalid", `{"text":"hello","attachment_ids":`+raw+"}")
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("send: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user