Files
schedtxt_api/internal/handler/message_test.go
T
phoenixandphoenix 77c950d299 tsk-24: Fixed tests (#25)
Closes #24

Reviewed-on: phoenix/textsender-api#25
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-11-10 17:42:41 +00:00

76 lines
2.1 KiB
Go

package handler
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.kundeng.us/phoenix/textsender-models/pkg/message"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
"git.kundeng.us/phoenix/textsender-api/internal/store/mock"
)
type CreateMessageRequest struct {
Content string `json:"content"`
UserId uuid.UUID `json:"user_id"`
}
func TestCreateMessageWithMock(t *testing.T) {
mockStore := mock.NewMockMessageStore()
handler := NewMessageHandler(mockStore)
testUserId := uuid.New()
testBody := CreateMessageRequest{Content: "Who could tell?", UserId: testUserId}
jsonValue, _ := json.Marshal(testBody)
req, _ := http.NewRequest("POST", endpoint.ADD_MESSAGE, strings.NewReader(string(jsonValue)))
rr := httptest.NewRecorder()
handler.AddMessage(rr, req)
assert.Equal(t, http.StatusCreated, rr.Code)
var response AddMessageResponse
err := json.Unmarshal(rr.Body.Bytes(), &response)
assert.NoError(t, err, "Error Creating message %v", err)
assert.NotEmpty(t, response.Data, "No Message created")
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
}
func TestGetMessageWithMock(t *testing.T) {
mockstore := mock.NewMockMessageStore()
testUserId := uuid.New()
testCon := message.Message{Content: "Who is the one that benefits?", UserId: testUserId}
ctx := t.Context()
if err := mockstore.CreateMessage(ctx, &testCon); err != nil {
assert.NoError(t, err, "Error creating message")
return
}
url := fmt.Sprintf("%s?user_id=%s", endpoint.GET_MESSAGE, testCon.UserId)
req, _ := http.NewRequest("GET", url, nil)
rr := httptest.NewRecorder()
messageHandler := NewMessageHandler(mockstore)
messageHandler.GetMessage(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
var response GetMessageResponse
err := json.Unmarshal(rr.Body.Bytes(), &response)
assert.NoError(t, err, "Error getting message %v", err)
assert.NotEmpty(t, response.Data, "No Message retrieved")
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
}