Skip to content

Commit

Permalink
Fix Teams tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Robi9 committed Dec 27, 2023
1 parent b4c2161 commit 0647d1c
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 49 deletions.
56 changes: 25 additions & 31 deletions handlers/teams/teams.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,9 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}

serviceURL := payload.ServiceUrl
path := strings.Split(payload.ServiceURL, "//")
serviceURL := path[1]

var urn urns.URN

// the list of events we deal with
Expand All @@ -178,9 +180,9 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
}

if payload.Type == "message" {
sender := payload.Conversation.ID
sender := strings.Split(payload.Conversation.ID, "a:")

urn, err = urns.NewTeamsURN(sender + ":serviceURL:" + serviceURL)
urn, err = urns.NewTeamsURN(sender[1] + ":" + path[1])
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
Expand All @@ -189,12 +191,12 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
attachmentURLs := make([]string, 0, 2)

for _, att := range payload.Attachments {
if att.ContentType != "" && att.ContentUrl != "" {
attachmentURLs = append(attachmentURLs, att.ContentUrl)
if att.ContentType != "" && att.ContentURL != "" {
attachmentURLs = append(attachmentURLs, att.ContentURL)
}
}

ev := h.Backend().NewIncomingMsg(channel, urn, text, clog).WithExternalID(payload.Id).WithReceivedOn(date)
ev := h.Backend().NewIncomingMsg(channel, urn, text, clog).WithExternalID(payload.ID).WithReceivedOn(date)
event := h.Backend().CheckExternalIDSeen(ev)

// add any attachment URL found
Expand All @@ -220,11 +222,6 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
return nil, nil
}

act := Activity{}

act.Text = "Create Conversation"
act.Type = "message"

bot := ChannelAccount{}

bot.ID = channel.StringConfigForKey("botID", "")
Expand All @@ -233,31 +230,28 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
members := []ChannelAccount{}

members = append(members, ChannelAccount{ID: userID, Role: payload.MembersAdded[0].Role})
tenantID := channel.StringConfigForKey("tenantID", "")

ConversationJson := &mtPayload{
Activity: act,
Bot: bot,
Members: members,
IsGroup: false,
TenantId: tenantID,
Bot: bot,
Members: members,
IsGroup: false,
}
jsonBody, err := json.Marshal(ConversationJson)
if err != nil {
return nil, err
}
token := channel.StringConfigForKey(courier.ConfigAuthToken, "")
req, err := http.NewRequest(http.MethodPost, serviceURL+"/v3/conversations", bytes.NewReader(jsonBody))
req, err := http.NewRequest(http.MethodPost, payload.ServiceURL+"/v3/conversations", bytes.NewReader(jsonBody))

if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)

_, respBody, err := handlers.RequestHTTP(req, clog)
if err != nil {
return nil, err
resp, respBody, err := handlers.RequestHTTP(req, clog)
if err != nil || resp.StatusCode/100 != 2 {
return nil, errors.New("unable to look up contact data")
}

var body ConversationAccount
Expand All @@ -266,8 +260,8 @@ func (h *handler) receiveEvent(ctx context.Context, channel courier.Channel, w h
if err != nil {
return nil, err
}

urn, err = urns.NewTeamsURN(body.ID + ":serviceURL:" + serviceURL)
conversationID := strings.Split(body.ID, "a:")
urn, err = urns.NewTeamsURN(conversationID[1] + ":" + serviceURL)
if err != nil {
return nil, handlers.WriteAndLogRequestError(ctx, h, channel, w, r, err)
}
Expand Down Expand Up @@ -318,22 +312,22 @@ type ConversationAccount struct {
AadObjectId string `json:"aadObjectId"`
}

type Attachment struct {
type mtAttachment struct {
ContentType string `json:"contentType"`
ContentUrl string `json:"contentUrl"`
ContentURL string `json:"contentUrl"`
Name string `json:"name,omitempty"`
}

type Activity struct {
Action string `json:"action,omitempty"`
Attachments []Attachment `json:"attachments,omitempty"`
ChannelId string `json:"channelId,omitempty"`
Attachments []mtAttachment `json:"attachments,omitempty"`
ChannelID string `json:"channelId,omitempty"`
Conversation ConversationAccount `json:"conversation,omitempty"`
Id string `json:"id,omitempty"`
ID string `json:"id,omitempty"`
MembersAdded []ChannelAccount `json:"membersAdded,omitempty"`
Name string `json:"name,omitempty"`
Recipient ChannelAccount `json:"recipient,omitempty"`
ServiceUrl string `json:"serviceUrl,omitempty"`
ServiceURL string `json:"serviceUrl,omitempty"`
Text string `json:"text"`
Type string `json:"type"`
Timestamp string `json:"timestamp,omitempty"`
Expand Down Expand Up @@ -361,7 +355,7 @@ func (h *handler) Send(ctx context.Context, msg courier.Msg, clog *courier.Chann
if err != nil {
logrus.WithField("channel_uuid", msg.Channel().UUID().String()).WithError(err).Error("Error while parsing the media URL")
}
payload.Attachments = append(payload.Attachments, Attachment{attType, attURL, filename})
payload.Attachments = append(payload.Attachments, mtAttachment{attType, attURL, filename})
}

if msg.Text() != "" {
Expand Down Expand Up @@ -412,7 +406,7 @@ func (h *handler) DescribeURN(ctx context.Context, channel courier.Channel, urn
req.Header.Set("Authorization", "Bearer "+accessToken)
resp, respBody, err := handlers.RequestHTTP(req, clog)
if err != nil {
return nil, fmt.Errorf("unable to look up contact data:%s\n%s", err, resp)
return nil, fmt.Errorf("unable to look up contact data:%v\n%v", err, resp)
}

// read our first and last name
Expand Down
59 changes: 42 additions & 17 deletions handlers/teams/teams_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@ package teams

import (
"context"
"io"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"

"github.com/buger/jsonparser"
"github.com/nyaruka/courier"
. "github.com/nyaruka/courier/handlers"
"github.com/nyaruka/courier/test"
Expand Down Expand Up @@ -127,7 +130,7 @@ var testCases = []ChannelHandleTestCase{
ExpectedRespStatus: 200,
ExpectedBodyContains: "Handled",
ExpectedMsgText: Sp("Hello World"),
ExpectedURN: "teams:a:2811:serviceURL:https://smba.trafficmanager.net/br/",
ExpectedURN: "teams:2811:smba.trafficmanager.net/br/",
ExpectedExternalID: "56834",
ExpectedDate: time.Date(2022, 6, 6, 16, 51, 00, 0000000, time.UTC),
Headers: map[string]string{"Authorization": "Bearer " + access_token},
Expand All @@ -141,7 +144,7 @@ var testCases = []ChannelHandleTestCase{
ExpectedBodyContains: "Handled",
ExpectedMsgText: Sp("Hello World"),
ExpectedAttachments: []string{"https://image-url/foo.png"},
ExpectedURN: "teams:a:2811:serviceURL:https://smba.trafficmanager.net/br/",
ExpectedURN: "teams:2811:smba.trafficmanager.net/br/",
ExpectedExternalID: "56834",
ExpectedDate: time.Date(2022, 6, 6, 16, 51, 00, 0000000, time.UTC),
Headers: map[string]string{"Authorization": "Bearer " + access_token},
Expand All @@ -155,7 +158,7 @@ var testCases = []ChannelHandleTestCase{
ExpectedBodyContains: "Handled",
ExpectedMsgText: Sp("Hello World"),
ExpectedAttachments: []string{"https://video-url/foo.mp4"},
ExpectedURN: "teams:a:2811:serviceURL:https://smba.trafficmanager.net/br/",
ExpectedURN: "teams:2811:smba.trafficmanager.net/br/",
ExpectedExternalID: "56834",
ExpectedDate: time.Date(2022, 6, 6, 16, 51, 00, 0000000, time.UTC),
Headers: map[string]string{"Authorization": "Bearer " + access_token},
Expand All @@ -169,7 +172,7 @@ var testCases = []ChannelHandleTestCase{
ExpectedBodyContains: "Handled",
ExpectedMsgText: Sp("Hello World"),
ExpectedAttachments: []string{"https://document-url/foo.pdf"},
ExpectedURN: "teams:a:2811:serviceURL:https://smba.trafficmanager.net/br/",
ExpectedURN: "teams:2811:smba.trafficmanager.net/br/",
ExpectedExternalID: "56834",
ExpectedDate: time.Date(2022, 6, 6, 16, 51, 00, 0000000, time.UTC),
Headers: map[string]string{"Authorization": "Bearer " + access_token},
Expand Down Expand Up @@ -221,6 +224,7 @@ func buildMockTeams() *httptest.Server {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
accessToken := r.Header.Get("Authorization")
tokenH := strings.Replace(accessToken, "Bearer ", "", 1)
// payload := r.GetBody
defer r.Body.Close()

// invalid auth token
Expand All @@ -234,6 +238,18 @@ func buildMockTeams() *httptest.Server {
}

if r.URL.Path == "/v3/conversations/a:2022/activities" {
byteBody, err := io.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
}
text, err := jsonparser.GetString(byteBody, "text")
if err != nil {
log.Fatal(err)
}
if text == "Error" {
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(`{"is_error": true}`))
}
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(`{"id":"1234567890"}`))
}
Expand Down Expand Up @@ -262,32 +278,37 @@ var defaultSendTestCases = []ChannelSendTestCase{
{
Label: "Plain Send",
MsgText: "Simple Message",
MsgURN: "teams:a:2022:serviceURL:https://smba.trafficmanager.net/br/",
MsgURN: "teams:2022:https://smba.trafficmanager.net/br/",
ExpectedMsgStatus: "W", ExpectedExternalID: "1234567890",
MockResponseBody: `{id:"1234567890"}`, MockResponseStatus: 200,
},
{Label: "Send Photo",
MsgURN: "teams:a:2022:serviceURL:https://smba.trafficmanager.net/br/", MsgAttachments: []string{"image/jpeg:https://foo.bar/image.jpg"},
MsgURN: "teams:2022:https://smba.trafficmanager.net/br/", MsgAttachments: []string{"image/jpeg:https://foo.bar/image.jpg"},
ExpectedMsgStatus: "W", ExpectedExternalID: "1234567890",
MockResponseBody: `{"id": "1234567890"}`, MockResponseStatus: 200,
},
{Label: "Send Video",
MsgURN: "teams:a:2022:serviceURL:https://smba.trafficmanager.net/br/", MsgAttachments: []string{"video/mp4:https://foo.bar/video.mp4"},
MsgURN: "teams:2022:https://smba.trafficmanager.net/br/", MsgAttachments: []string{"video/mp4:https://foo.bar/video.mp4"},
ExpectedMsgStatus: "W", ExpectedExternalID: "1234567890",
MockResponseBody: `{"id": "1234567890"}`, MockResponseStatus: 200,
},
{Label: "Send Document",
MsgURN: "teams:a:2022:serviceURL:https://smba.trafficmanager.net/br/", MsgAttachments: []string{"application/pdf:https://foo.bar/document.pdf"},
MsgURN: "teams:2022:https://smba.trafficmanager.net/br/", MsgAttachments: []string{"application/pdf:https://foo.bar/document.pdf"},
ExpectedMsgStatus: "W", ExpectedExternalID: "1234567890",
MockResponseBody: `{"id": "1234567890"}`, MockResponseStatus: 200,
},
{Label: "ID Error",
MsgText: "Error", MsgURN: "teams:2022:smba.trafficmanager.net/br/",
ExpectedMsgStatus: "E",
MockResponseBody: `{"is_error": true}`, MockResponseStatus: 200,
},
}

func newSendTestCases(testSendCases []ChannelSendTestCase, url string) []ChannelSendTestCase {
var newtestSendCases []ChannelSendTestCase
for _, tc := range testSendCases {
spTC := strings.Split(tc.MsgURN, ":serviceURL:")
newURN := spTC[0] + ":serviceURL:" + url + "/"
spTC := strings.Split(tc.MsgURN, ":")
newURN := spTC[0] + ":" + spTC[1] + ":" + url + "/"
tc.MsgURN = newURN
newtestSendCases = append(newtestSendCases, tc)
}
Expand All @@ -299,23 +320,27 @@ func TestSending(t *testing.T) {
map[string]interface{}{courier.ConfigAuthToken: access_token, "tenantID": "cba321", "botID": "0123", "appID": "1596"})

serviceTM := buildMockTeams()
newSendTestCases := newSendTestCases(defaultSendTestCases, serviceTM.URL)
url := strings.Split(serviceTM.URL, "http://")
newSendTestCases := newSendTestCases(defaultSendTestCases, url[1])
RunChannelSendTestCases(t, defaultChannel, newHandler(), newSendTestCases, nil, nil)
serviceTM.Close()
}

func TestDescribe(t *testing.T) {
server := buildMockTeams()
clog := courier.NewChannelLog(courier.ChannelLogTypeUnknown, testChannels[0], nil)
url := strings.Split(server.URL, "http://")

channel := testChannels[0]
handler := newHandler().(courier.URNDescriber)
logger := courier.NewChannelLog(courier.ChannelLogTypeUnknown, channel, nil)
tcs := []struct {
urn urns.URN
metadata map[string]string
}{{urns.URN("teams:a:2022:serviceURL:" + string(server.URL) + "/"), map[string]string{"name": "John Doe"}}}
urn urns.URN
expectedMetadata map[string]string
}{{urns.URN("teams:2022:" + string(url[1]) + "/"), map[string]string{"name": "John Doe"}}}

for _, tc := range tcs {
metadata, _ := handler.DescribeURN(context.Background(), testChannels[0], tc.urn, clog)
assert.Equal(t, metadata, tc.metadata)
metadata, _ := handler.DescribeURN(context.Background(), testChannels[0], tc.urn, logger)
assert.Equal(t, metadata, tc.expectedMetadata)
}
server.Close()
}
2 changes: 1 addition & 1 deletion handlers/weniwebchat/weniwebchat.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func (h *handler) Send(ctx context.Context, msg courier.Msg, clog *courier.Chann
MediaURL: attachmentURL,
}
} else {
logrus.WithField("channel_uuid", msg.Channel().UUID().String()).Error("unknown attachment mime type: %s", mimeType)
logrus.WithField("channel_uuid", msg.Channel().UUID().String()).Error("unknown attachment mime type: ", mimeType)
status.SetStatus(courier.MsgFailed)
break attachmentsLoop
}
Expand Down

0 comments on commit 0647d1c

Please sign in to comment.