forked from mtusi2026/mtusi2026lab3
204 lines
7.9 KiB
Go
204 lines
7.9 KiB
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
type sampleRequest struct {
|
|
Username *string `json:"username"`
|
|
DisplayName *string `json:"display_name"`
|
|
Password *string `json:"password"`
|
|
}
|
|
|
|
func decodeTestApp() *App { return &App{maxBody: maxBodyBytes} }
|
|
|
|
func TestDecodeJSONAcceptsDocumentedObject(t *testing.T) {
|
|
app := decodeTestApp()
|
|
body := `{"username":"alice","display_name":"Алиса","password":"long-enough-secret"}`
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
|
|
request.Header.Set("Content-Type", "application/json; charset=utf-8")
|
|
var destination sampleRequest
|
|
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem != nil {
|
|
t.Fatalf("decodeJSON rejected a valid body: %v", problem)
|
|
}
|
|
if destination.Username == nil || *destination.Username != "alice" {
|
|
t.Fatalf("decoded value = %+v", destination)
|
|
}
|
|
}
|
|
|
|
func TestDecodeJSONRejectsContractViolations(t *testing.T) {
|
|
app := decodeTestApp()
|
|
cases := []struct {
|
|
name string
|
|
body string
|
|
contentType string
|
|
status int
|
|
}{
|
|
{"empty", "", "application/json", http.StatusBadRequest},
|
|
{"whitespace only", " \n", "application/json", http.StatusBadRequest},
|
|
{"malformed", `{"username":`, "application/json", http.StatusBadRequest},
|
|
{"array instead of object", `[]`, "application/json", http.StatusBadRequest},
|
|
{"string instead of object", `"x"`, "application/json", http.StatusBadRequest},
|
|
{"unknown field", `{"username":"a","display_name":"b","password":"c","extra":1}`, "application/json", http.StatusBadRequest},
|
|
{"duplicate field", `{"username":"a","username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
|
|
{"uppercase alias", `{"Username":"a","display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
|
|
{"alias beside correct key", `{"username":"a","Username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
|
|
{"wrong type", `{"username":1,"display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
|
|
{"two values", `{"username":"a","display_name":"b","password":"c"}{}`, "application/json", http.StatusBadRequest},
|
|
{"wrong content type", `{"username":"a","display_name":"b","password":"c"}`, "text/plain", http.StatusUnsupportedMediaType},
|
|
{"malformed content type", `{"username":"a","display_name":"b","password":"c"}`, "application/json; charset", http.StatusUnsupportedMediaType},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(tc.body))
|
|
request.Header.Set("Content-Type", tc.contentType)
|
|
var destination sampleRequest
|
|
problem := app.decodeJSON(request, &destination, "username", "display_name", "password")
|
|
if problem == nil {
|
|
t.Fatal("decodeJSON accepted an invalid body")
|
|
}
|
|
if problem.status != tc.status {
|
|
t.Fatalf("status = %d, want %d", problem.status, tc.status)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestDecodeJSONRejectsInvalidUTF8(t *testing.T) {
|
|
app := decodeTestApp()
|
|
body := append([]byte(`{"username":"`), 0xff, 0xfe)
|
|
body = append(body, []byte(`","display_name":"b","password":"c"}`)...)
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", bytes.NewReader(body))
|
|
request.Header.Set("Content-Type", "application/json")
|
|
var destination sampleRequest
|
|
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem == nil || problem.status != http.StatusBadRequest {
|
|
t.Fatalf("invalid UTF-8 was not rejected with 400: %v", problem)
|
|
}
|
|
}
|
|
|
|
func TestDecodeJSONRejectsOversizedBody(t *testing.T) {
|
|
app := decodeTestApp()
|
|
app.maxBody = 16
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":"`+strings.Repeat("x", 64)+`"}`))
|
|
request.Header.Set("Content-Type", "application/json")
|
|
var destination sampleRequest
|
|
if problem := app.decodeJSON(request, &destination, "username"); problem == nil || problem.status != http.StatusRequestEntityTooLarge {
|
|
t.Fatalf("oversized body = %v, want 413", problem)
|
|
}
|
|
}
|
|
|
|
func TestUsernameValidation(t *testing.T) {
|
|
valid := []string{"abc", "a_b9", strings.Repeat("a", 32)}
|
|
for _, value := range valid {
|
|
if problem := validateUsername(value); problem != nil {
|
|
t.Fatalf("validateUsername(%q) = %v", value, problem)
|
|
}
|
|
}
|
|
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "a-b", "a b", "aбв", "abc\n"}
|
|
for _, value := range invalid {
|
|
if problem := validateUsername(value); problem == nil {
|
|
t.Fatalf("validateUsername accepted %q", value)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLengthValidationCountsCodePoints(t *testing.T) {
|
|
if problem := validateDisplayName(strings.Repeat("😀", 100)); problem != nil {
|
|
t.Fatalf("100 code points rejected: %v", problem)
|
|
}
|
|
if problem := validateDisplayName(strings.Repeat("😀", 101)); problem == nil {
|
|
t.Fatal("101 code points accepted")
|
|
}
|
|
if problem := validateDisplayName(" "); problem == nil {
|
|
t.Fatal("blank display_name accepted")
|
|
}
|
|
|
|
if problem := validateMessageText(strings.Repeat("я", 4000)); problem != nil {
|
|
t.Fatalf("4000 code points rejected: %v", problem)
|
|
}
|
|
if problem := validateMessageText(strings.Repeat("я", 4001)); problem == nil {
|
|
t.Fatal("4001 code points accepted")
|
|
}
|
|
if problem := validateMessageText(" \t\n"); problem == nil {
|
|
t.Fatal("blank message accepted")
|
|
}
|
|
|
|
if problem := validatePassword(strings.Repeat("p", 12)); problem != nil {
|
|
t.Fatalf("12-character password rejected: %v", problem)
|
|
}
|
|
if problem := validatePassword(strings.Repeat("p", 11)); problem == nil {
|
|
t.Fatal("11-character password accepted")
|
|
}
|
|
if problem := validatePassword(strings.Repeat("p", 128)); problem != nil {
|
|
t.Fatalf("128-character password rejected: %v", problem)
|
|
}
|
|
if problem := validatePassword(strings.Repeat("p", 129)); problem == nil {
|
|
t.Fatal("129-character password accepted")
|
|
}
|
|
if problem := validatePassword(strings.Repeat(" ", 12)); problem == nil {
|
|
t.Fatal("whitespace password accepted")
|
|
}
|
|
}
|
|
|
|
func TestPageParams(t *testing.T) {
|
|
valid := map[string][2]any{
|
|
"": {50, ""},
|
|
"?limit=1": {1, ""},
|
|
"?limit=100": {100, ""},
|
|
"?limit=7&cursor=x": {7, "x"},
|
|
}
|
|
for query, want := range valid {
|
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
|
|
limit, cursor, problem := decodeTestApp().pageParams(request)
|
|
if problem != nil {
|
|
t.Fatalf("pageParams(%q) = %v", query, problem)
|
|
}
|
|
if limit != want[0].(int) || cursor != want[1].(string) {
|
|
t.Fatalf("pageParams(%q) = %d,%q", query, limit, cursor)
|
|
}
|
|
}
|
|
invalid := []string{"?limit=0", "?limit=101", "?limit=abc", "?limit=", "?limit=1&limit=2", "?cursor=", "?cursor=a&cursor=b", "?limit=1;cursor=x"}
|
|
for _, query := range invalid {
|
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
|
|
if _, _, problem := decodeTestApp().pageParams(request); problem == nil {
|
|
t.Fatalf("pageParams accepted %q", query)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestBearerTokenParsing(t *testing.T) {
|
|
token := strings.Repeat("a", 43)
|
|
cases := map[string]string{
|
|
"Bearer " + token: token,
|
|
"bearer " + token: token,
|
|
"BEARER " + token: token,
|
|
}
|
|
for header, want := range cases {
|
|
got, ok := bearerToken(header)
|
|
if !ok || got != want {
|
|
t.Fatalf("bearerToken(%q) = %q,%v", header, got, ok)
|
|
}
|
|
}
|
|
for _, header := range []string{"", "Bearer", "Bearer ", "Basic abc", "Bearer a b", "Token " + token} {
|
|
if _, ok := bearerToken(header); ok {
|
|
t.Fatalf("bearerToken accepted %q", header)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestErrorEnvelopeShape(t *testing.T) {
|
|
envelope := errorEnvelope{Error: errorBody{Code: "invalid_request", Message: "x", RequestID: "id"}}
|
|
data, err := json.Marshal(envelope)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if string(data) != `{"error":{"code":"invalid_request","message":"x","request_id":"id"}}` {
|
|
t.Fatalf("unexpected error JSON: %s", data)
|
|
}
|
|
}
|