forked from mtusi2026/mtusi2026lab2
174 lines
6.2 KiB
Go
174 lines
6.2 KiB
Go
package messenger
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
|
)
|
|
|
|
var errDependency = errors.New("dependency unavailable")
|
|
|
|
type repositoryStub struct {
|
|
pingErr error
|
|
userByID model.User
|
|
userByIDErr error
|
|
credentials model.UserCredentials
|
|
credentialsErr error
|
|
}
|
|
|
|
func (s repositoryStub) Ping(context.Context) error { return s.pingErr }
|
|
func (repositoryStub) CreateUser(context.Context, string, string, string) (model.User, error) {
|
|
return model.User{}, nil
|
|
}
|
|
func (s repositoryStub) UserByID(context.Context, string) (model.User, error) {
|
|
return s.userByID, s.userByIDErr
|
|
}
|
|
func (s repositoryStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
|
|
return s.credentials, s.credentialsErr
|
|
}
|
|
func (repositoryStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
|
|
return model.Chat{}, nil
|
|
}
|
|
func (repositoryStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
|
|
return model.Chat{}, nil
|
|
}
|
|
func (repositoryStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
|
|
return nil, false, nil
|
|
}
|
|
func (repositoryStub) CreateMessage(context.Context, string, string, string) (model.Message, error) {
|
|
return model.Message{}, nil
|
|
}
|
|
func (repositoryStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
|
return nil, false, nil
|
|
}
|
|
|
|
type sessionStub struct {
|
|
pingErr error
|
|
userID string
|
|
userIDErr error
|
|
}
|
|
|
|
func (s sessionStub) Ping(context.Context) error { return s.pingErr }
|
|
func (sessionStub) Create(context.Context, string, time.Duration) (string, time.Time, error) {
|
|
return "token", time.Now().Add(time.Hour), nil
|
|
}
|
|
func (s sessionStub) UserID(context.Context, string) (string, error) { return s.userID, s.userIDErr }
|
|
func (sessionStub) Delete(context.Context, string) error { return nil }
|
|
|
|
type passwordsStub struct {
|
|
verified bool
|
|
err error
|
|
}
|
|
|
|
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
|
|
func (passwordsStub) DummyHash() string { return "hash" }
|
|
func (s passwordsStub) Verify(string, string) (bool, error) {
|
|
return s.verified, s.err
|
|
}
|
|
|
|
func TestReadinessReturnsUnavailableForDependencyFailure(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
repo repositoryStub
|
|
sessions sessionStub
|
|
}{
|
|
{name: "postgres", repo: repositoryStub{pingErr: errDependency}},
|
|
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
server := newTestServer(tt.repo, tt.sessions, passwordsStub{})
|
|
response := serveRequest(server, http.MethodGet, "/health/ready", "")
|
|
if response.Code != http.StatusServiceUnavailable {
|
|
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestBusinessRequestReturnsUnavailableForDependencyFailure(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
repo repositoryStub
|
|
sessions sessionStub
|
|
}{
|
|
{name: "valkey", sessions: sessionStub{userIDErr: errDependency}},
|
|
{name: "postgres", repo: repositoryStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
server := newTestServer(tt.repo, tt.sessions, passwordsStub{})
|
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
|
request.Header.Set("Authorization", "Bearer valid-token")
|
|
response := httptest.NewRecorder()
|
|
server.Handler().ServeHTTP(response, request)
|
|
if response.Code != http.StatusServiceUnavailable {
|
|
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestAuthenticationChallenges(t *testing.T) {
|
|
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
|
bearer := serveRequest(server, http.MethodGet, "/api/v1/users/me", "")
|
|
if bearer.Code != http.StatusUnauthorized || bearer.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
|
t.Fatalf("business challenge = %d %q", bearer.Code, bearer.Header().Get("WWW-Authenticate"))
|
|
}
|
|
|
|
repository := repositoryStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
|
|
server = newTestServer(repository, sessionStub{}, passwordsStub{verified: false})
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
|
request.SetBasicAuth("user", "wrong-password")
|
|
response := httptest.NewRecorder()
|
|
server.Handler().ServeHTTP(response, request)
|
|
if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
|
t.Fatalf("session challenge = %d %q", response.Code, response.Header().Get("WWW-Authenticate"))
|
|
}
|
|
}
|
|
|
|
func TestSessionCreationRejectsChunkedBody(t *testing.T) {
|
|
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
|
request.ContentLength = -1
|
|
request.SetBasicAuth("user", "password")
|
|
response := httptest.NewRecorder()
|
|
server.Handler().ServeHTTP(response, request)
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
|
}
|
|
}
|
|
|
|
func TestRegistrationRejectsWhitespacePassword(t *testing.T) {
|
|
server := newTestServer(repositoryStub{}, sessionStub{}, passwordsStub{})
|
|
response := serveRequest(server, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":" "}`)
|
|
if response.Code != http.StatusBadRequest {
|
|
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
|
}
|
|
}
|
|
|
|
func newTestServer(repository Repository, sessions SessionStore, passwords Passwords) *Server {
|
|
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
|
|
return NewServer(logger, repository, sessions, passwords, time.Hour, time.Second, "8081")
|
|
}
|
|
|
|
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
|
|
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
|
if body != "" {
|
|
request.Header.Set("Content-Type", "application/json")
|
|
}
|
|
response := httptest.NewRecorder()
|
|
server.Handler().ServeHTTP(response, request)
|
|
return response
|
|
}
|