Files
schedtxt_api/internal/handler/contact_test.go
T
phoenixandphoenix 0d252bc261 tsk-51: Send message endpoint (#52)
Closes #51

Reviewed-on: phoenix/textsender-api#52
Co-authored-by: phoenix <kundeng00@pm.me>
Co-committed-by: phoenix <kundeng00@pm.me>
2025-12-10 21:35:02 +00:00

91 lines
2.4 KiB
Go

package handler
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"git.kundeng.us/phoenix/textsender-models/tx0/contact"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"git.kundeng.us/phoenix/textsender-api/internal/db"
"git.kundeng.us/phoenix/textsender-api/internal/handler/endpoint"
"git.kundeng.us/phoenix/textsender-api/internal/store/mock"
)
type Request struct {
PhoneNumber string
UserId uuid.UUID
}
func TestCreateContactWithMock(t *testing.T) {
mockstore := mock.NewMockContactStore()
apiApp, err := GetApp()
assert.NoError(t, err, "Error getting app")
handler := NewContactHandler(apiApp, mockstore)
testUserId := uuid.New()
testBody := Request{PhoneNumber: "+12335403383", UserId: testUserId}
jsonValue, _ := json.Marshal(testBody)
req, _ := http.NewRequest("POST", endpoint.ADD_CONTACT_ENDPOINT, strings.NewReader(string(jsonValue)))
rr := httptest.NewRecorder()
handler.AddContact(rr, req)
assert.Equal(t, http.StatusCreated, rr.Code)
var response AddContactResponse
err = json.Unmarshal(rr.Body.Bytes(), &response)
assert.NoError(t, err, "Error Creating contact %v", err)
assert.NotEmpty(t, response.Data, "No Contact created")
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
}
func TestGetContactWithMock(t *testing.T) {
mockstore := mock.NewMockContactStore()
testUserId := uuid.New()
testCon := contact.Contact{PhoneNumber: "+12335403383", UserId: testUserId}
ctx := t.Context()
if err := mockstore.CreateContact(ctx, &testCon); err != nil {
assert.NoError(t, err, "Error creating contact")
return
}
url := fmt.Sprintf("%s?user_id=%s", endpoint.GET_CONTACT, testCon.UserId)
req, _ := http.NewRequest("GET", url, nil)
rr := httptest.NewRecorder()
apiApp, err := GetApp()
assert.NoError(t, err, "Error getting app")
contactHandler := NewContactHandler(apiApp, mockstore)
contactHandler.GetContact(rr, req)
assert.Equal(t, http.StatusOK, rr.Code)
var response GetContactResponse
err = json.Unmarshal(rr.Body.Bytes(), &response)
assert.NoError(t, err, "Error getting contact %v", err)
assert.NotEmpty(t, response.Data, "No Contact retrieved")
assert.NotNil(t, response.Data[0].Id, "Id should not be nil")
}
func resetTestDB(t *testing.T) {
t.Helper()
_, err := db.Pool.Exec(context.Background(), "DELETE FROM contacts")
if err != nil {
t.Fatalf("Failed to reset test database: %v", err)
}
}