Files
gochat/internal/handler/api/v1/whatsapp_call_handler_test.go
T

153 lines
7.1 KiB
Go

package v1
import (
"bytes"
"context"
"encoding/json"
"mime/multipart"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
"github.com/gochat/gochat/internal/model"
channelmodel "github.com/gochat/gochat/internal/model/channel"
"github.com/gochat/gochat/internal/repository"
"github.com/gochat/gochat/internal/service"
)
type fakeHandlerWhatsAppCallProvider struct{}
func (fakeHandlerWhatsAppCallProvider) InitiateCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) (string, error) {
return "wacid_handler", nil
}
func (fakeHandlerWhatsAppCallProvider) PreAcceptCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) error {
return nil
}
func (fakeHandlerWhatsAppCallProvider) AcceptCall(context.Context, *channelmodel.ChannelWhatsApp, string, string) error {
return nil
}
func (fakeHandlerWhatsAppCallProvider) RejectCall(context.Context, *channelmodel.ChannelWhatsApp, string) error {
return nil
}
func (fakeHandlerWhatsAppCallProvider) TerminateCall(context.Context, *channelmodel.ChannelWhatsApp, string) error {
return nil
}
func (fakeHandlerWhatsAppCallProvider) SendCallPermissionRequest(context.Context, *channelmodel.ChannelWhatsApp, string, string) (string, error) {
return "wamid.req", nil
}
func setupWhatsAppCallHandlerTest(t *testing.T) (*gin.Engine, *gorm.DB, *model.Account, *model.Conversation) {
t.Helper()
gin.SetMode(gin.TestMode)
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
require.NoError(t, err)
require.NoError(t, db.AutoMigrate(&model.Account{}, &model.Inbox{}, &model.Contact{}, &model.Conversation{}, &model.Call{}, &model.Message{}, &model.Attachment{}, &channelmodel.ChannelWhatsApp{}))
account := &model.Account{Name: "Voice Account", Status: "active"}
require.NoError(t, db.Create(account).Error)
inbox := &model.Inbox{AccountID: account.ID, Name: "WhatsApp", ChannelType: "whatsapp", ChannelID: 1, ChannelConfig: `{"voice_enabled":true}`}
require.NoError(t, db.Create(inbox).Error)
channel := &channelmodel.ChannelWhatsApp{AccountID: account.ID, InboxID: inbox.ID, PhoneNumber: "+15550000000", PhoneNumberID: "phone-1", BusinessAccountID: "waba-1", AccessToken: "token", Provider: "whatsapp_cloud", ProviderConfig: `{"calling_enabled":true}`}
require.NoError(t, db.Create(channel).Error)
inbox.ChannelID = channel.ID
require.NoError(t, db.Save(inbox).Error)
contact := &model.Contact{AccountID: account.ID, Name: "Ada", PhoneNumber: "+15551234567"}
require.NoError(t, db.Create(contact).Error)
displayID := uint(42)
conversation := &model.Conversation{AccountID: account.ID, InboxID: inbox.ID, ContactID: contact.ID, DisplayID: &displayID, Status: "open", ChannelType: "whatsapp", Channel: "whatsapp"}
require.NoError(t, db.Create(conversation).Error)
handler := NewWhatsAppCallHandler(service.NewWhatsAppCallService(repository.NewWhatsAppCallRepo(db), fakeHandlerWhatsAppCallProvider{}))
router := gin.New()
router.Use(func(c *gin.Context) {
c.Set("user_id", uint(7))
c.Next()
})
router.GET("/api/v1/accounts/:account_id/whatsapp_calls/:id", handler.Show)
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/initiate", handler.Initiate)
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:id/accept", handler.Accept)
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:id/reject", handler.Reject)
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:id/terminate", handler.Terminate)
router.POST("/api/v1/accounts/:account_id/whatsapp_calls/:id/upload_recording", handler.UploadRecording)
return router, db, account, conversation
}
func TestWhatsAppCallHandler_AccountRoutesMatchFrontendAPI(t *testing.T) {
router, db, account, conversation := setupWhatsAppCallHandlerTest(t)
w := httptest.NewRecorder()
body := []byte(`{"conversation_id":42,"sdp_offer":"sdp_offer"}`)
req := httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/initiate", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
resp := whatsappDecodeMap(t, w.Body.Bytes())
require.Equal(t, "calling", resp["status"])
require.Equal(t, "wacid_handler", resp["call_id"])
var call model.Call
require.NoError(t, db.Where("account_id = ? AND conversation_id = ?", account.ID, conversation.ID).First(&call).Error)
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID), nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
show := whatsappDecodeMap(t, w.Body.Bytes())
require.Equal(t, "wacid_handler", show["call_id"])
require.Equal(t, "whatsapp", show["provider"])
}
func TestWhatsAppCallHandler_ActionsAndRecordingPayloads(t *testing.T) {
router, db, account, conversation := setupWhatsAppCallHandlerTest(t)
call := &model.Call{AccountID: account.ID, InboxID: 1, ConversationID: conversation.ID, ContactID: conversation.ContactID, Provider: "whatsapp", Direction: "incoming", ProviderCallID: "wacid_in", Status: "ringing", CallerType: "Contact", CallerID: conversation.ContactID, CallDirection: "inbound"}
require.NoError(t, db.Create(call).Error)
message := &model.Message{AccountID: account.ID, InboxID: 1, ConversationID: conversation.ID, ContentType: "voice_call", MessageType: "incoming"}
require.NoError(t, db.Create(message).Error)
require.NoError(t, db.Model(call).Update("message_id", message.ID).Error)
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/accept", bytes.NewReader([]byte(`{"sdp_answer":"sdp_answer"}`)))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "in-progress", whatsappDecodeMap(t, w.Body.Bytes())["status"])
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/terminate", nil)
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "completed", whatsappDecodeMap(t, w.Body.Bytes())["status"])
var upload bytes.Buffer
writer := multipart.NewWriter(&upload)
part, err := writer.CreateFormFile("recording", "call.webm")
require.NoError(t, err)
_, err = part.Write([]byte("audio"))
require.NoError(t, err)
require.NoError(t, writer.Close())
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPost, "/api/v1/accounts/1/whatsapp_calls/"+whatsappItoaUint(call.ID)+"/upload_recording", &upload)
req.Header.Set("Content-Type", writer.FormDataContentType())
router.ServeHTTP(w, req)
require.Equal(t, http.StatusOK, w.Code)
require.Equal(t, "uploaded", whatsappDecodeMap(t, w.Body.Bytes())["status"])
}
func whatsappDecodeMap(t *testing.T, body []byte) map[string]any {
t.Helper()
var out map[string]any
require.NoError(t, json.Unmarshal(body, &out))
return out
}
func whatsappItoaUint(id uint) string {
return strconv.FormatUint(uint64(id), 10)
}