Closes #24 Reviewed-on: phoenix/textsender-api#25 Co-authored-by: phoenix <kundeng00@pm.me> Co-committed-by: phoenix <kundeng00@pm.me>
86 lines
2.3 KiB
Go
86 lines
2.3 KiB
Go
package handler
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"git.kundeng.us/phoenix/textsender-models/pkg/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()
|
|
handler := NewContactHandler(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()
|
|
|
|
contactHandler := NewContactHandler(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)
|
|
}
|
|
}
|