Private
Public Access
1
0

Add 'mock/' from commit '2041d3ce6377da091eca17cf9d8ad176a3024616'

git-subtree-dir: mock
git-subtree-mainline: 8216d7c706
git-subtree-split: 2041d3ce63
This commit is contained in:
2025-09-06 19:35:49 -07:00
20 changed files with 2661 additions and 0 deletions

12
mock/web/request_types.go Normal file
View File

@@ -0,0 +1,12 @@
package web
type AuthenticationRequest struct {
Username string `json:"username"`
Password string `json:"password"`
}
type SendMessageRequest struct {
ConversationGUID string `json:"guid"`
Body string `json:"body"`
TransferGUIDs []string `json:"fileTransferGUIDs"`
}

View File

@@ -0,0 +1,5 @@
package web
type UploadAttachmentResponse struct {
TransferGUID string `json:"fileTransferGUID"`
}

476
mock/web/server.go Normal file
View File

@@ -0,0 +1,476 @@
package web
import (
"bufio"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"go.buzzert.net/kordophone-mock/model"
"go.buzzert.net/kordophone-mock/server"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/gorilla/websocket"
)
type MockHTTPServerConfiguration struct {
AuthEnabled bool
}
type MockHTTPServer struct {
Server server.Server
mux http.ServeMux
authEnabled bool
}
type AuthError struct {
message string
}
func (e *AuthError) Error() string {
return e.message
}
func (m *MockHTTPServer) logRequest(r *http.Request, extras ...string) {
log.Debug().Msgf("%s %s %s", r.Method, r.URL.Path, strings.Join(extras, " "))
}
func (m *MockHTTPServer) checkAuthentication(r *http.Request) error {
if !m.authEnabled {
return nil
}
// Check for Authorization header
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return &AuthError{"Missing Authorization header"}
}
// Check for "Bearer" prefix
if authHeader[:7] != "Bearer " {
return &AuthError{"Invalid Authorization header"}
}
// Check for valid token
token := authHeader[7:]
if !m.Server.CheckBearerToken(token) {
return &AuthError{"Invalid token"}
}
return nil
}
func (m *MockHTTPServer) requireAuthentication(w http.ResponseWriter, r *http.Request) bool {
if !m.authEnabled {
return true
}
if err := m.checkAuthentication(r); err != nil {
log.Error().Err(err).Msg("Error checking authentication")
http.Error(w, err.Error(), http.StatusUnauthorized)
return false
}
return true
}
func (m *MockHTTPServer) handleVersion(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s", m.Server.Version())
}
func (m *MockHTTPServer) handleStatus(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
fmt.Fprintf(w, "OK")
}
func (m *MockHTTPServer) handleConversations(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
convos := m.Server.Conversations()
// Encode convos as JSON
jsonData, err := json.Marshal(convos)
if err != nil {
log.Error().Err(err).Msg("Error marshalling conversations")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write JSON to response
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func (m *MockHTTPServer) handleMessages(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
guid := r.URL.Query().Get("guid")
if len(guid) == 0 {
log.Error().Msg("handleMessage: Got empty guid parameter")
http.Error(w, "no guid parameter specified", http.StatusBadRequest)
return
}
conversation, err := m.Server.ConversationForGUID(guid)
if err != nil {
log.Error().Err(err).Msgf("handleMessage: Error getting conversation (%s)", guid)
http.Error(w, "conversation not found", http.StatusBadRequest)
return
}
beforeDate := r.URL.Query().Get("beforeDate")
beforeGUID := r.URL.Query().Get("beforeMessageGUID")
afterGUID := r.URL.Query().Get("afterMessageGUID")
limit := r.URL.Query().Get("limit")
stringOrNil := func(s string) *string {
if len(s) == 0 {
return nil
}
return &s
}
dateOrNil := func(s string) *model.Date {
if len(s) == 0 {
return nil
}
t, _ := time.Parse(time.RFC3339, s)
date := model.Date(t)
return &date
}
intOrNil := func(s string) *int {
if len(s) == 0 {
return nil
}
i, _ := strconv.Atoi(s)
return &i
}
query := server.MessagesQuery{
Limit: intOrNil(limit),
BeforeDate: dateOrNil(beforeDate),
BeforeGUID: stringOrNil(beforeGUID),
AfterGUID: stringOrNil(afterGUID),
ConversationGUID: conversation.Guid,
}
messages := m.Server.PerformMessageQuery(&query)
jsonData, err := json.Marshal(messages)
if err != nil {
log.Error().Err(err).Msg("Error marshalling messages")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write JSON to response
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func (m *MockHTTPServer) handleAuthenticate(w http.ResponseWriter, r *http.Request) {
// Decode request body as AuthenticationRequest
var authReq AuthenticationRequest
err := json.NewDecoder(r.Body).Decode(&authReq)
if err != nil {
log.Error().Err(err).Msg("Authenticate: Error decoding request body")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Authenticate
token, err := m.Server.Authenticate(authReq.Username, authReq.Password)
if err != nil {
log.Error().Err(err).Msg("Authenticate: Error authenticating")
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
// Write response
w.Header().Set("Content-Type", "application/json")
// Encode token as JSON
jsonData, err := json.Marshal(token)
if err != nil {
log.Error().Err(err).Msg("Error marshalling token")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write JSON to response
w.Write(jsonData)
}
func (m *MockHTTPServer) handleNotFound(w http.ResponseWriter, r *http.Request) {
log.Error().Msgf("Unimplemented API endpoint: %s %s", r.Method, r.URL.Path)
http.NotFound(w, r)
}
func (m *MockHTTPServer) handleSendMessage(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
// Decode request body as SendMessageRequest
var sendMessageReq SendMessageRequest
err := json.NewDecoder(r.Body).Decode(&sendMessageReq)
if err != nil {
log.Error().Err(err).Msg("SendMessage: Error decoding request body")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Find conversation
conversation, err := m.Server.ConversationForGUID(sendMessageReq.ConversationGUID)
if err != nil {
log.Error().Err(err).Msgf("SendMessage: Error finding conversation (%s)", sendMessageReq.ConversationGUID)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Create Message
message := model.Message{
Guid: uuid.New().String(),
Text: sendMessageReq.Body,
Date: model.Date(time.Now()),
AttachmentGUIDs: sendMessageReq.TransferGUIDs,
Sender: nil, // me
}
// Send message
m.Server.SendMessage(conversation, message)
// Encode response as JSON
jsonData, err := json.Marshal(message)
if err != nil {
log.Error().Err(err).Msg("Error marshalling response")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write JSON to response
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func (m *MockHTTPServer) handlePollUpdates(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
// TODO: This should block if we don't have updates for that seq yet.
seq := -1
seqString := r.URL.Query().Get("seq")
if len(seqString) > 0 {
var err error
seq, err = strconv.Atoi(seqString)
if err != nil {
log.Error().Err(err).Msg("FetchUpdates: Error parsing seq")
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
// Fetch updates (blocking)
updates := m.Server.FetchUpdatesBlocking(seq)
if len(updates) == 0 {
// return 205 (Nothing to report)
w.WriteHeader(http.StatusResetContent)
log.Info().Msg("FetchUpdates: Nothing to report")
} else {
// Encode updates as JSON
jsonData, err := json.Marshal(updates)
if err != nil {
log.Error().Err(err).Msg("Error marshalling updates")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write JSON to response
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
}
func (m *MockHTTPServer) handleMarkConversation(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
guid := r.URL.Query().Get("guid")
if len(guid) == 0 {
log.Error().Msg("handleMarkConversation: Got empty guid parameter")
http.Error(w, "no guid parameter specified", http.StatusBadRequest)
return
}
// Find conversation
convo, err := m.Server.ConversationForGUID(guid)
if err != nil {
log.Error().Err(err).Msgf("handleMarkConversation: Error finding conversation (%s)", guid)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Mark conversation
m.Server.MarkConversationAsRead(convo)
// Respond 200
w.WriteHeader(http.StatusOK)
}
func (m *MockHTTPServer) handleFetchAttachment(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
guid := r.URL.Query().Get("guid")
if guid == "" {
log.Error().Msg("fetchAttachment: Missing 'guid' parameter")
http.Error(w, "no guid parameter specified", http.StatusBadRequest)
return
}
reader, err := m.Server.FetchAttachment(guid)
if err != nil {
log.Error().Msgf("fetchAttachment: Could not load attachment from store: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dw := bufio.NewWriter(w)
_, err = dw.ReadFrom(reader)
if err != nil {
log.Error().Msgf("fetchAttachment: Error reading attachment data: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (m *MockHTTPServer) handleUploadAttachment(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
filename := r.URL.Query().Get("filename")
if filename == "" {
log.Error().Msgf("uploadAttachment: filename not provided")
http.Error(w, "filename not provided", http.StatusBadRequest)
return
}
guid, err := m.Server.UploadAttachment(filename, r.Body)
if err != nil {
log.Error().Msgf("uploadAttachment: error storing attachment: %s", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
response := UploadAttachmentResponse{
TransferGUID: *guid,
}
jsonData, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(jsonData)
}
func (m *MockHTTPServer) handleUpdates(w http.ResponseWriter, r *http.Request) {
if !m.requireAuthentication(w, r) {
return
}
upgrader := websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Error().Err(err).Msg("websocket upgrade failed")
return
}
m.handleUpdatesWebsocket(c)
}
func (m *MockHTTPServer) handleUpdatesWebsocket(c *websocket.Conn) {
// Fetch updates continuously
defer c.Close()
// Start a goroutine to handle incoming messages (pings, usually)
go func() {
for {
_, _, err := c.ReadMessage()
if err != nil {
log.Error().Err(err).Msg("WebSocket read error")
return
}
}
}()
for {
// Fetch updates (blocking)
updates := m.Server.FetchUpdatesBlocking(-1)
// Send updates to client
err := c.WriteJSON(updates)
if err != nil {
log.Error().Err(err).Msg("handleUpdatesWebsocket: Error sending updates to client (probably disconnected)")
return
}
}
}
func (m *MockHTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.logRequest(r, r.URL.Query().Encode())
m.mux.ServeHTTP(w, r)
}
func NewMockHTTPServer(config MockHTTPServerConfiguration) *MockHTTPServer {
this := MockHTTPServer{
Server: *server.NewServer(),
mux: *http.NewServeMux(),
authEnabled: config.AuthEnabled,
}
// Redirect /api/* to /*
this.mux.Handle("/api/", http.StripPrefix("/api", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, r.URL.Path, http.StatusMovedPermanently)
})))
this.mux.Handle("/version", http.HandlerFunc(this.handleVersion))
this.mux.Handle("/conversations", http.HandlerFunc(this.handleConversations))
this.mux.Handle("/status", http.HandlerFunc(this.handleStatus))
this.mux.Handle("/authenticate", http.HandlerFunc(this.handleAuthenticate))
this.mux.Handle("/messages", http.HandlerFunc(this.handleMessages))
this.mux.Handle("/pollUpdates", http.HandlerFunc(this.handlePollUpdates))
this.mux.Handle("/sendMessage", http.HandlerFunc(this.handleSendMessage))
this.mux.Handle("/markConversation", http.HandlerFunc(this.handleMarkConversation))
this.mux.Handle("/attachment", http.HandlerFunc(this.handleFetchAttachment))
this.mux.Handle("/uploadAttachment", http.HandlerFunc(this.handleUploadAttachment))
this.mux.Handle("/updates", http.HandlerFunc(this.handleUpdates))
this.mux.Handle("/", http.HandlerFunc(this.handleNotFound))
return &this
}

731
mock/web/server_test.go Normal file
View File

@@ -0,0 +1,731 @@
package web_test
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"go.buzzert.net/kordophone-mock/data"
"go.buzzert.net/kordophone-mock/model"
"go.buzzert.net/kordophone-mock/server"
"go.buzzert.net/kordophone-mock/web"
"github.com/gorilla/websocket"
)
func TestVersion(t *testing.T) {
s := httptest.NewServer(web.NewMockHTTPServer(web.MockHTTPServerConfiguration{}))
resp, err := http.Get(s.URL + "/version")
if err != nil {
t.Fatalf("TestVersion error: %s", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
if string(body) != server.VERSION {
t.Fatalf("Unexpected return value: %s (expected %s)", body, "1.0")
}
}
func TestStatus(t *testing.T) {
s := httptest.NewServer(web.NewMockHTTPServer(web.MockHTTPServerConfiguration{}))
resp, err := http.Get(s.URL + "/status")
if err != nil {
t.Fatalf("TestStatus error: %s", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
if string(body) != "OK" {
t.Fatalf("Unexpected return value: %s (expected %s)", body, "OK")
}
}
func TestConversations(t *testing.T) {
server := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{})
httpServer := httptest.NewServer(server)
conversation := model.Conversation{
Date: model.Date(time.Now()),
Participants: []string{"Alice", "Bob"},
UnreadCount: 1,
LastMessagePreview: "Hello world",
Guid: "1234567890",
}
server.Server.AddConversation(conversation)
resp, err := http.Get(httpServer.URL + "/conversations")
if err != nil {
t.Fatalf("TestConversations error: %s", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
var convos []model.Conversation
err = json.Unmarshal(body, &convos)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %s", err)
}
if len(convos) != 1 {
t.Fatalf("Unexpected number of conversations: %d (expected %d)", len(convos), 1)
}
testConversation := &convos[0]
if testConversation.Equal(&conversation) != true {
t.Fatalf("Unexpected conversation: %v (expected %v)", convos[0], conversation)
}
}
func TestMessages(t *testing.T) {
server := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{})
httpServer := httptest.NewServer(server)
const sender = "Alice"
const text = "This is a test."
conversation := model.Conversation{
Date: model.Date(time.Now()),
Participants: []string{sender},
UnreadCount: 1,
Guid: "1234567890",
}
server.Server.AddConversation(conversation)
message := model.Message{
Text: text,
Sender: &conversation.Participants[0],
Date: model.Date(time.Now()),
}
server.Server.AppendMessageToConversation(&conversation, message)
resp, err := http.Get(httpServer.URL + "/messages?guid=" + conversation.Guid)
if err != nil {
t.Fatalf("TestMessages error: %s", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
var messages []model.Message
err = json.Unmarshal(body, &messages)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %s", err)
}
if len(messages) != 1 {
t.Fatalf("Unexpected num messages: %d (expected %d)", len(messages), 1)
}
fetchedMessage := messages[0]
if fetchedMessage.Text != message.Text {
t.Fatalf("Unexpected message text: %s (expected %s)", fetchedMessage.Text, message.Text)
}
if *fetchedMessage.Sender != *message.Sender {
t.Fatalf("Unexpected message sender: %s (expected %s)", *fetchedMessage.Sender, *message.Sender)
}
}
func TestAuthentication(t *testing.T) {
s := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{AuthEnabled: true})
httpServer := httptest.NewServer(s)
// First, try authenticated request and make sure it fails
resp, err := http.Get(httpServer.URL + "/status")
if err != nil {
t.Fatalf("TestAuthentication status error: %s", err)
}
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("Unexpected status code: %d (expected %d)", resp.StatusCode, http.StatusUnauthorized)
}
tryAuthenticate := func(username string, password string) *http.Response {
authRequest := web.AuthenticationRequest{
Username: username,
Password: password,
}
authRequestJSON, err := json.Marshal(authRequest)
if err != nil {
t.Fatalf("Error marshalling JSON: %s", err)
}
resp, err := http.Post(httpServer.URL+"/authenticate", "application/json", io.NopCloser(bytes.NewReader(authRequestJSON)))
if err != nil {
t.Fatalf("TestAuthentication error: %s", err)
}
return resp
}
// Send authentication request with bad credentials
resp = tryAuthenticate("bad", "credentials")
if resp.StatusCode == http.StatusOK {
t.Fatalf("Unexpected status code: %d (expected %d)", resp.StatusCode, http.StatusUnauthorized)
}
// Now try good credentials
resp = tryAuthenticate(server.AUTH_USERNAME, server.AUTH_PASSWORD)
if resp.StatusCode != http.StatusOK {
t.Fatalf("Unexpected status code: %d (expected %d)", resp.StatusCode, http.StatusOK)
}
// Decode the token from the body.
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
var authToken model.AuthToken
err = json.Unmarshal(body, &authToken)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %s, body: %s", err, body)
}
if authToken.SignedToken == "" {
t.Fatalf("Unexpected empty signed token")
}
// Send a request with the signed token
req, err := http.NewRequest(http.MethodGet, httpServer.URL+"/status", nil)
if err != nil {
t.Fatalf("Error creating request: %s", err)
}
req.Header.Set("Authorization", "Bearer "+authToken.SignedToken)
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("Error sending request: %s", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Unexpected status code: %d (expected %d)", resp.StatusCode, http.StatusUnauthorized)
}
body, err = io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
if string(body) != "OK" {
t.Fatalf("Unexpected body: %s (expected %s)", body, "OK")
}
}
func TestUpdates(t *testing.T) {
s := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{AuthEnabled: false})
httpServer := httptest.NewServer(s)
messageSeq := 0
// Mock conversation
guid := "1234567890"
conversation := model.Conversation{
Date: model.Date(time.Now()),
Participants: []string{"Alice"},
UnreadCount: 0,
Guid: guid,
}
s.Server.AddConversation(conversation)
// Receive a message
message := model.Message{
Text: "This is a test.",
Sender: &conversation.Participants[0],
Date: model.Date(time.Now()),
}
// This should enqueue an update item
s.Server.ReceiveMessage(&conversation, message)
resp, err := http.Get(httpServer.URL + fmt.Sprintf("/pollUpdates?seq=%d", messageSeq))
if err != nil {
t.Fatalf("TestUpdates error: %s", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Unexpected status code: %d (expected %d)", resp.StatusCode, http.StatusOK)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
var updates []model.UpdateItem
err = json.Unmarshal(body, &updates)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %s", err)
}
if len(updates) != 1 {
t.Fatalf("Unexpected num updates: %d (expected %d)", len(updates), 1)
}
update := updates[0]
// Message seq should be >= messageSeq
messageSeq = update.MessageSequenceNumber
if messageSeq != 1 {
t.Fatalf("Unexpected message seq: %d (expected >= 0)", messageSeq)
}
if update.Conversation.Guid != conversation.Guid {
t.Fatalf("Unexpected conversation guid: %s (expected %s)", update.Conversation.Guid, conversation.Guid)
}
if update.Message.Text != message.Text {
t.Fatalf("Unexpected message text: %s (expected %s)", update.Message.Text, message.Text)
}
}
type MessageUpdateError struct {
Message string
}
func (e MessageUpdateError) Error() string {
return e.Message
}
func TestUpdatesWebsocket(t *testing.T) {
s := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{AuthEnabled: false})
httpServer := httptest.NewServer(s)
// Mock conversation
guid := "1234567890"
conversation := model.Conversation{
Date: model.Date(time.Now()),
Participants: []string{"Alice"},
UnreadCount: 0,
Guid: guid,
}
s.Server.AddConversation(conversation)
// Receive a message
message := model.Message{
Text: "This is a test.",
Sender: &conversation.Participants[0],
Date: model.Date(time.Now()),
}
// Open websocket connection
wsURL := "ws" + strings.TrimPrefix(httpServer.URL, "http") + "/updates"
ws, _, err := websocket.DefaultDialer.Dial(wsURL, nil)
if err != nil {
t.Fatalf("Error opening websocket: %s", err)
}
// Await messages on the websocket
messageReceived := make(chan bool)
errorEncountered := make(chan error)
go func() {
// Read from websocket
var updates []model.UpdateItem
err := ws.ReadJSON(&updates)
if err != nil {
errorEncountered <- err
return
} else {
if len(updates) != 1 {
errorEncountered <- MessageUpdateError{
fmt.Sprintf("Unexpected num updates: %d (expected %d)", len(updates), 1),
}
return
}
update := updates[0]
if update.Conversation.Guid != conversation.Guid {
errorEncountered <- MessageUpdateError{
fmt.Sprintf("Unexpected conversation guid: %s (expected %s)", update.Conversation.Guid, conversation.Guid),
}
return
}
if update.Message.Text != message.Text {
errorEncountered <- MessageUpdateError{
fmt.Sprintf("Unexpected message text: %s (expected %s)", update.Message.Text, message.Text),
}
return
}
messageReceived <- true
}
}()
// sleep for a bit to allow the websocket to connect
time.Sleep(100 * time.Millisecond)
// This should enqueue an update item
s.Server.ReceiveMessage(&conversation, message)
// Await expectation
select {
case <-messageReceived:
// COOL
case err := <-errorEncountered:
t.Fatalf("Error encountered reading from websocket: %s", err)
case <-time.After(1 * time.Second):
t.Fatalf("Timed out waiting for websocket message")
}
}
func TestMarkConversation(t *testing.T) {
s := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{AuthEnabled: false})
httpServer := httptest.NewServer(s)
// Mock conversation
guid := "1234567890"
conversation := model.Conversation{
Date: model.Date(time.Now()),
Participants: []string{"Alice"},
UnreadCount: 0,
Guid: guid,
}
s.Server.AddConversation(conversation)
// Receive message to mark as unread
message := model.Message{
Text: "This is a test.",
Sender: &conversation.Participants[0],
Date: model.Date(time.Now()),
}
s.Server.ReceiveMessage(&conversation, message)
if convo, _ := s.Server.ConversationForGUID(guid); convo.UnreadCount != 1 {
t.Fatalf("Unexpected unread count: %d (expected %d)", convo.UnreadCount, 1)
}
// Mark conversation as read
resp, err := http.Post(httpServer.URL+"/markConversation?guid="+guid, "", nil)
if err != nil {
t.Fatalf("TestMarkConversation error: %s", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Unexpected status code: %d (expected %d)", resp.StatusCode, http.StatusOK)
}
if convo, _ := s.Server.ConversationForGUID(guid); convo.UnreadCount != 0 {
t.Fatalf("Unexpected unread count: %d (expected %d)", convo.UnreadCount, 0)
}
}
func TestMessageQueries(t *testing.T) {
s := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{AuthEnabled: false})
httpServer := httptest.NewServer(s)
// Mock conversation
guid := "1234567890"
conversation := model.Conversation{
Date: model.Date(time.Now()),
Participants: []string{"Alice"},
UnreadCount: 0,
Guid: guid,
}
s.Server.AddConversation(conversation)
// Mock messages
numMessages := 20
for i := 0; i < numMessages; i++ {
message := data.GenerateRandomMessage(conversation.Participants)
s.Server.AppendMessageToConversation(&conversation, message)
}
// Pick a pivot message from the sorted list
sortedMessages := s.Server.MessagesForConversation(&conversation)
pivotMessage := sortedMessages[len(sortedMessages)/2]
// Query messages before the pivot, test limit also
limitMessageCount := 5
resp, err := http.Get(httpServer.URL + fmt.Sprintf("/messages?guid=%s&beforeMessageGUID=%s&limit=%d", guid, pivotMessage.Guid, limitMessageCount))
if err != nil {
t.Fatalf("TestMessageQueries error: %s", err)
}
// Decode response
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
var messages []model.Message
err = json.Unmarshal(body, &messages)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %s", err)
}
if len(messages) != limitMessageCount {
t.Fatalf("Unexpected num messages: %d (expected %d)", len(messages), limitMessageCount)
}
// Make sure before query is exclusive of the pivot message
for _, message := range messages {
if message.Guid == pivotMessage.Guid {
t.Fatalf("Found pivot guid in before query: %s (expected != %s)", message.Guid, pivotMessage.Guid)
}
}
// Make sure messages are actually before the pivot
for _, message := range messages {
if message.Date.After(pivotMessage.Date) {
t.Fatalf("Unexpected message date.")
}
}
// Query messages after the pivot
resp, err = http.Get(httpServer.URL + fmt.Sprintf("/messages?guid=%s&afterMessageGUID=%s", guid, pivotMessage.Guid))
if err != nil {
t.Fatalf("TestMessageQueries error: %s", err)
}
// Decode response
body, err = io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
messages = []model.Message{}
err = json.Unmarshal(body, &messages)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %s", err)
}
// Make sure after query is exclusive of the pivot message
for _, message := range messages {
if message.Guid == pivotMessage.Guid {
t.Fatalf("Found pivot guid in after query: %s (expected != %s)", message.Guid, pivotMessage.Guid)
}
}
// Make sure messages are actually after the pivot
for _, message := range messages {
if message.Date.Before(pivotMessage.Date) {
t.Fatalf("Unexpected message date")
}
}
}
func trySendMessage(t *testing.T, httpServer *httptest.Server, request web.SendMessageRequest) string {
// Encode as json
requestJSON, err := json.Marshal(request)
if err != nil {
t.Fatalf("Error marshalling JSON: %s", err)
}
// Send request
resp, err := http.Post(httpServer.URL+"/sendMessage", "application/json", io.NopCloser(bytes.NewReader(requestJSON)))
if err != nil {
t.Fatalf("TestSendMessage error: %s", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("Unexpected status code: %d (expected %d)", resp.StatusCode, http.StatusOK)
}
// Decode response
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
var response model.Message
err = json.Unmarshal(body, &response)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %s", err)
}
if response.Guid == "" {
t.Fatalf("Unexpected empty guid")
}
return response.Guid
}
func TestSendMessage(t *testing.T) {
s := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{AuthEnabled: false})
httpServer := httptest.NewServer(s)
// Mock conversation
guid := "1234567890"
conversation := model.Conversation{
Date: model.Date(time.Now()),
Participants: []string{"Alice"},
UnreadCount: 0,
Guid: guid,
}
s.Server.AddConversation(conversation)
// Send it
request := web.SendMessageRequest{
ConversationGUID: guid,
Body: "hello there",
TransferGUIDs: []string{},
}
responseGuid := trySendMessage(t, httpServer, request)
// Make sure message is present
messages := s.Server.MessagesForConversation(&conversation)
found := false
for _, message := range messages {
if message.Guid == responseGuid {
found = true
break
}
}
if found != true {
t.Fatalf("Message not found in conversation")
}
}
func tryUploadAttachment(t *testing.T, testData string, httpServer *httptest.Server) string {
// Send upload request
attachmentDataReader := strings.NewReader(testData)
resp, err := http.Post(httpServer.URL+"/uploadAttachment?filename=test.txt", "application/data", attachmentDataReader)
if err != nil {
t.Fatalf("Error uploading attachment: %s", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
var response web.UploadAttachmentResponse
err = json.Unmarshal(body, &response)
if err != nil {
t.Fatalf("Error decoding response: %s", err)
}
return response.TransferGUID
}
func tryFetchAttachment(t *testing.T, httpServer *httptest.Server, guid string) []byte {
resp, err := http.Get(httpServer.URL + fmt.Sprintf("/attachment?guid=%s", guid))
if err != nil {
t.Fatalf("Error fetching attachment: %s", err)
}
responseData, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error reading attachment data: %s", err)
}
return responseData
}
func TestAttachments(t *testing.T) {
s := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{AuthEnabled: false})
httpServer := httptest.NewServer(s)
testData := "hello world!"
guid := tryUploadAttachment(t, testData, httpServer)
// Cleanup after ourselves
defer s.Server.DeleteAttachment(guid)
// Fetch it back
responseData := tryFetchAttachment(t, httpServer, guid)
if string(responseData) != testData {
t.Fatalf("Didn't get expected response data: %s (got %s)", testData, responseData)
}
}
func TestSendMessageWithAttachment(t *testing.T) {
s := web.NewMockHTTPServer(web.MockHTTPServerConfiguration{AuthEnabled: false})
httpServer := httptest.NewServer(s)
// Mock conversation
conversation := model.Conversation{
Date: model.Date(time.Now()),
Participants: []string{"Alice"},
UnreadCount: 0,
Guid: "123456789",
}
s.Server.AddConversation(conversation)
testData := "attachment data"
attachmentGuid := tryUploadAttachment(t, testData, httpServer)
messageRequest := web.SendMessageRequest{
ConversationGUID: conversation.Guid,
Body: "",
TransferGUIDs: []string{attachmentGuid},
}
sentGuid := trySendMessage(t, httpServer, messageRequest)
// See if our message has that attachment
resp, err := http.Get(httpServer.URL + "/messages?guid=" + conversation.Guid)
if err != nil {
t.Fatalf("TestMessages error: %s", err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Error decoding body: %s", body)
}
var messages []model.Message
err = json.Unmarshal(body, &messages)
if err != nil {
t.Fatalf("Error unmarshalling JSON: %s", err)
}
if len(messages) != 1 {
t.Fatalf("Unexpected num messages: %d (expected %d)", len(messages), 1)
}
onlyMessage := messages[0]
if onlyMessage.Guid != sentGuid {
t.Fatalf("Unexpected guid: %s (expected %s)", onlyMessage.Guid, sentGuid)
}
if len(onlyMessage.AttachmentGUIDs) != 1 {
t.Fatalf("Message returned didn't have expected attachment guids")
}
if onlyMessage.AttachmentGUIDs[0] != attachmentGuid {
t.Fatalf("Message returned had wrong attachment guid: %s (expected %s)", onlyMessage.AttachmentGUIDs[0], attachmentGuid)
}
// See if we get data back
fetchedData := tryFetchAttachment(t, httpServer, attachmentGuid)
if string(fetchedData) != testData {
t.Fatalf("Sent message attachment had incorrect data: %s (expected %s)", fetchedData, testData)
}
}